From bdffd4b653bdfae6ab3e5e7ed2e0a3ed89d09210 Mon Sep 17 00:00:00 2001 From: SolidityX <> Date: Wed, 18 Jan 2023 17:17:55 +0530 Subject: [PATCH] contracts added --- Crowdsale/IPUX-crowdsale-contract.sol | 213 +++ DEX/EtherDex.sol | 467 ++++++ DEX/TronDex.sol | 518 +++++++ ERC1155 Tokens/PIZ TOKEN.sol | 553 +++++++ ERC20 Tokens/Alteredux.sol | 456 ++++++ ERC20 Tokens/Azuma Coin.sol | 354 +++++ ERC20 Tokens/CENTI Token.sol | 557 +++++++ ERC20 Tokens/Cointorox.sol | 364 +++++ ERC20 Tokens/EROX-token.sol | 568 +++++++ ERC20 Tokens/EnvoyChain.sol | 726 +++++++++ ERC20 Tokens/Ezoow.sol | 337 ++++ ERC20 Tokens/FSM.sol | 356 +++++ ERC20 Tokens/FavorToken.sol | 1363 +++++++++++++++++ ERC20 Tokens/IPUX token.sol | 371 +++++ ERC20 Tokens/SE7EN.sol | 549 +++++++ ERC20 Tokens/Sevo Token.sol | 435 ++++++ .../South East Trading Investment Token.sol | 363 +++++ ERC20 Tokens/Storag Coin.sol | 434 ++++++ ERC20 Tokens/Topia Shares.sol | 498 ++++++ ERC20 Tokens/USERCoin.sol | 378 +++++ ERC865 Tokens/PIZ TOKEN.sol | 548 +++++++ FlashLoan/FlashLoan.sol | 108 ++ Gambling/Trontopia Vault Game.sol | 945 ++++++++++++ Gambling/hyperLOTTO smart contract.sol | 267 ++++ Game/Double Ether (with its own token).sol | 481 ++++++ Game/HXXD game.sol | 281 ++++ Game/Place It - Pixel Game.sol | 763 +++++++++ NFT - Non Fungible Tokens/Niftymoji.sol | 1320 ++++++++++++++++ PoC/Fish Trade.sol | 362 +++++ PoC/SSL Certificate Authority Management.sol | 313 ++++ Stable Coin/True INR Stable coin.sol | 643 ++++++++ Staking/Diamond Dividend Trontopia.sol | 515 +++++++ Staking/HyperETH-Staking-Smart-Contract.sol | 829 ++++++++++ staking/basicStaking.sol | 207 --- 34 files changed, 17235 insertions(+), 207 deletions(-) create mode 100644 Crowdsale/IPUX-crowdsale-contract.sol create mode 100644 DEX/EtherDex.sol create mode 100644 DEX/TronDex.sol create mode 100644 ERC1155 Tokens/PIZ TOKEN.sol create mode 100644 ERC20 Tokens/Alteredux.sol create mode 100644 ERC20 Tokens/Azuma Coin.sol create mode 100644 ERC20 Tokens/CENTI Token.sol create mode 100644 ERC20 Tokens/Cointorox.sol create mode 100644 ERC20 Tokens/EROX-token.sol create mode 100644 ERC20 Tokens/EnvoyChain.sol create mode 100644 ERC20 Tokens/Ezoow.sol create mode 100644 ERC20 Tokens/FSM.sol create mode 100644 ERC20 Tokens/FavorToken.sol create mode 100644 ERC20 Tokens/IPUX token.sol create mode 100644 ERC20 Tokens/SE7EN.sol create mode 100644 ERC20 Tokens/Sevo Token.sol create mode 100644 ERC20 Tokens/South East Trading Investment Token.sol create mode 100644 ERC20 Tokens/Storag Coin.sol create mode 100644 ERC20 Tokens/Topia Shares.sol create mode 100644 ERC20 Tokens/USERCoin.sol create mode 100644 ERC865 Tokens/PIZ TOKEN.sol create mode 100644 FlashLoan/FlashLoan.sol create mode 100644 Gambling/Trontopia Vault Game.sol create mode 100644 Gambling/hyperLOTTO smart contract.sol create mode 100644 Game/Double Ether (with its own token).sol create mode 100644 Game/HXXD game.sol create mode 100644 Game/Place It - Pixel Game.sol create mode 100644 NFT - Non Fungible Tokens/Niftymoji.sol create mode 100644 PoC/Fish Trade.sol create mode 100644 PoC/SSL Certificate Authority Management.sol create mode 100644 Stable Coin/True INR Stable coin.sol create mode 100644 Staking/Diamond Dividend Trontopia.sol create mode 100644 Staking/HyperETH-Staking-Smart-Contract.sol delete mode 100644 staking/basicStaking.sol diff --git a/Crowdsale/IPUX-crowdsale-contract.sol b/Crowdsale/IPUX-crowdsale-contract.sol new file mode 100644 index 0000000..c9a2ffa --- /dev/null +++ b/Crowdsale/IPUX-crowdsale-contract.sol @@ -0,0 +1,213 @@ +pragma solidity 0.5.2; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + .----------------. .----------------. .----------------. .----------------. +| .--------------. | | .--------------. | | .--------------. | | .--------------. | +| | _____ | | | | ______ | | | | _____ _____ | | | | ____ ____ | | +| | |_ _| | | | | |_ __ \ | | | ||_ _||_ _|| | | | |_ _||_ _| | | +| | | | | | | | | |__) | | | | | | | | | | | | | \ \ / / | | +| | | | | | | | | ___/ | | | | | ' ' | | | | | > `' < | | +| | _| |_ | | | | _| |_ | | | | \ `--' / | | | | _/ /'`\ \_ | | +| | |_____| | | | | |_____| | | | | `.__.' | | | | |____||____| | | +| | | | | | | | | | | | | | | | +| '--------------' | | '--------------' | | '--------------' | | '--------------' | + '----------------' '----------------' '----------------' '----------------' + + __________________________________________________________________ + __ __ + / ) / / ) / + ---/--------)__----__-----------__-/--------\--------__---/----__- + / / ) / )| /| / / / \ / ) / /___) + _(____/___/_____(___/_|/_|/__(___/_______(____/___(___(_/___(___ _ + + + +// ---------------------------------------------------------------------------- +// 'IPUX' Crowdsale contract with following features +// => Token address change +// => SafeMath implementation +// => Ether sent to owner immediately +// => Phased ICO +// +// Copyright (c) 2019 TradeWeIPUX Limited ( https://ipux.io ) +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- + +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } +} + + +interface TokenRecipient { function transfer(address _to, uint256 _value) external; } + +contract IPUXcrowdsale is owned { + + /*============================== + = TECHNICAL SPECIFICATIONS = + =============================== + => ICO period 1 start: 15 Jan 2019 00:00:00 GMT + => ICO period 1 end: 17 Feb 2019 00:00:00 GMT + => ICO period 1 bonus: 30% + => ICO period 2 start: 01 Mar 2019 00:00:00 GMT + => ICO period 2 end: 31 Mar 2019 00:00:00 GMT + => ICO period 2 bonus: 20% + => ICO period 3 start: 15 Apr 2019 00:00:00 GMT + => ICO period 3 end: 30 Apr 2019 00:00:00 GMT + + => Token distribution only if ICO phases are going on. Else, it will accept ether but no tokens given + => There is no minimum or maximum of contrubution + => No acceptance of ether if hard cap is reached + */ + + + /*============================== + = PUBLIC VARIABLES = + ==============================*/ + address public tokenAddress; + uint256 public tokenDecimal; + using SafeMath for uint256; + TokenRecipient tokenContract = TokenRecipient(tokenAddress); + + /*============================== + = ICO VARIABLES = + ==============================*/ + uint256 public icoPeriod1start = 1547510400; //15 Jan 2019 00:00:00 GMT + uint256 public icoPeriod1end = 1550361600; //17 Feb 2019 00:00:00 GMT + uint256 public icoPeriod2start = 1551398400; //01 Mar 2019 00:00:00 GMT + uint256 public icoPeriod2end = 1553990400; //31 Mar 2019 00:00:00 GMT + uint256 public icoPeriod3start = 1555286400; //15 Apr 2019 00:00:00 GMT + uint256 public icoPeriod3end = 1556582400; //30 Apr 2019 00:00:00 GMT + uint256 public softcap = 70000 ether; + uint256 public hardcap = 400000 ether; + uint256 public fundRaised = 0; + uint256 public exchangeRate = 50; //1 ETH = 50 Tokens which equals to 0.02 ETH / token + + + + /*============================== + = PUBLIC FUNCTIONS = + ==============================*/ + + /** + * @notice Constructor function, which actually does not do anything + */ + constructor () public { } + + /** + * @notice Function to update the token address + * @param _tokenAddress Address of the token + */ + function updateToken(address _tokenAddress, uint256 _tokenDecimal) public onlyOwner { + require(_tokenAddress != address(0), 'Address is invalid'); + tokenAddress = _tokenAddress; + tokenDecimal = _tokenDecimal; + } + + /** + * @notice Payble fallback function which accepts ether and sends tokens to caller according to ETH amount + */ + function () payable external { + // no acceptance of ether if hard cap is reached + require(fundRaised < hardcap, 'hard cap is reached'); + // token distribution only if ICO is going on. Else, it will accept ether but no tokens given + if((icoPeriod1start < now && icoPeriod1end > now) || (icoPeriod2start < now && icoPeriod2end > now) || icoPeriod3start < now && icoPeriod3end > now){ + // calculate token amount to be sent, as pe weiamount * exchangeRate + uint256 token = msg.value.mul(exchangeRate); + // adding purchase bonus if application + uint256 finalTokens = token.add(calculatePurchaseBonus(token)); + // makes the token transfers + tokenContract.transfer(msg.sender, finalTokens); + } + fundRaised += msg.value; + // transfer ether to owner + owner.transfer(msg.value); + } + + /** + * @notice Internal function to calculate the purchase bonus + * @param token Amount of total tokens + * @return uint256 total payable purchase bonus + */ + function calculatePurchaseBonus(uint256 token) internal view returns(uint256){ + if(icoPeriod1start < now && icoPeriod1end > now){ + return token.mul(30).div(100); //30% bonus in period 1 + } + else if(icoPeriod2start < now && icoPeriod2end > now){ + return token.mul(20).div(100); //20% bonus in period 2 + } + else{ + return 0; // No bonus otherwise + } + } + + /** + * @notice Just in rare case, owner wants to transfer Ether from contract to owner address + */ + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + +} diff --git a/DEX/EtherDex.sol b/DEX/EtherDex.sol new file mode 100644 index 0000000..d1643bd --- /dev/null +++ b/DEX/EtherDex.sol @@ -0,0 +1,467 @@ +pragma solidity 0.5.13; /* + + + + + ___________________________________________________________________ + _ _ ______ + | | / / / + --|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) + __/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + + + ███████╗ █████╗ ███████╗██╗ ██╗ ██████╗ ███████╗██╗ ██╗ + ██╔════╝██╔══██╗██╔════╝╚██╗ ██╔╝ ██╔══██╗██╔════╝╚██╗██╔╝ + █████╗ ███████║███████╗ ╚████╔╝ ██║ ██║█████╗ ╚███╔╝ + ██╔══╝ ██╔══██║╚════██║ ╚██╔╝ ██║ ██║██╔══╝ ██╔██╗ + ███████╗██║ ██║███████║ ██║ ██████╔╝███████╗██╔╝ ██╗ + ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ + + + + + +------------------------------------------------------------------------------------------------------ + Copyright (c) 2019 Onwards Easy DEX Inc. ( https://xxxxxxxx.io ) + Contract designed with ❤ by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------------------------------------------ +*/ + + +//******************************************************************* +//------------------------ SafeMath Library ------------------------- +//******************************************************************* +library SafeMath { + /** + * @dev Returns the addition of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `+` operator. + * + * Requirements: + * - Addition cannot overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, "SafeMath: addition overflow"); + + return c; + } + + /** + * @dev Returns the subtraction of two unsigned integers, reverting on + * overflow (when the result is negative). + * + * Counterpart to Solidity's `-` operator. + * + * Requirements: + * - Subtraction cannot overflow. + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, "SafeMath: subtraction overflow"); + uint256 c = a - b; + + return c; + } + + /** + * @dev Returns the multiplication of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `*` operator. + * + * Requirements: + * - Multiplication cannot overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + // Gas optimization: this is cheaper than requiring 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 + if (a == 0) { + return 0; + } + + uint256 c = a * b; + require(c / a == b, "SafeMath: multiplication overflow"); + + return c; + } + + /** + * @dev Returns the integer division of two unsigned integers. Reverts on + * division by zero. The result is rounded towards zero. + * + * Counterpart to Solidity's `/` operator. Note: this function uses a + * `revert` opcode (which leaves remaining gas untouched) while Solidity + * uses an invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // Solidity only automatically asserts when dividing by 0 + require(b > 0, "SafeMath: division by zero"); + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + + return c; + } + + /** + * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), + * Reverts when dividing by zero. + * + * Counterpart to Solidity's `%` operator. This function uses a `revert` + * opcode (which leaves remaining gas untouched) while Solidity uses an + * invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + require(b != 0, "SafeMath: modulo by zero"); + return a % b; + } +} + + +interface ERC20Essential +{ + + function transfer(address _to, uint256 _amount) external returns (bool); + function transferFrom(address _from, address _to, uint256 _amount) external returns (bool); + +} + + + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address public owner; + address private newOwner; + + + event OwnershipTransferred(uint256 curTime, address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner, 'Only owner can call this function'); + _; + } + + + function onlyOwnerTransferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner, 'Only new owner can call this function'); + emit OwnershipTransferred(now, owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +contract EasyDEX is owned { + using SafeMath for uint256; + bool public safeGuard; // To hault all non owner functions in case of imergency - by default false + address public feeAccount; //the account that will receive fees + uint public tradingFee = 300; // 300 = 0.3% + + //referrals + uint256 public refPercent = 10; // percent to calculate referal bonous - by default 10% of trading fee + + mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether) + mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature) + mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled) + + /* Mapping to track referrer. The second address is the address of referrer, the Up-line/ Sponsor */ + mapping (address => address) public referrers; + /* Mapping to track referrer bonus for all the referrers */ + mapping (address => uint) public referrerBonusBalance; + + event Order(uint256 curTime, address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, address user); + event Cancel(uint256 curTime, address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, address user, uint8 v, bytes32 r, bytes32 s); + event Trade( uint256 curTime, address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give, uint256 orderBookID); + event Deposit(uint256 curTime, address token, address user, uint amount, uint balance); + event Withdraw(uint256 curTime, address token, address user, uint amount, uint balance); + event OwnerWithdrawCommission(address indexed owner, address indexed tokenAddress, uint256 amount); + + // Events to track ether transfer to referrers + event ReferrerBonus(address indexed referer, address indexed trader, uint256 referralBonus, uint256 timestamp ); + event ReferrerBonusWithdrawn(address indexed referrer, uint256 indexed amount); + + + + constructor() public { + feeAccount = msg.sender; + } + + function changeSafeguardStatus() onlyOwner public + { + if (safeGuard == false) + { + safeGuard = true; + } + else + { + safeGuard = false; + } + } + + //Calculate percent and return result + function calculatePercentage(uint256 PercentOf, uint256 percentTo ) internal pure returns (uint256) + { + uint256 factor = 100000; //so to make 1000 = 1% + require(percentTo <= factor, 'percentTo must be less than factor'); + uint256 c = PercentOf.mul(percentTo).div(factor); + return c; + } + + + + + // contract accepts incoming ether - this needed in case owner want to fund refPool + function() payable external { } + + + function changeFeeAccount(address feeAccount_) public onlyOwner { + feeAccount = feeAccount_; + } + + function changetradingFee(uint tradingFee_) public onlyOwner{ + require(tradingFee_ <= 10000, 'trading fee can not be more than 100%'); + tradingFee = tradingFee_; + } + + function availableOwnerCommissionEther() public view returns(uint256){ + //assress 0x0 only holds ether as fee + return tokens[address(0)][feeAccount]; + } + + function availableOwnerCommissionToken(address tokenAddress) public view returns(uint256){ + //assress 0x0 only holds ether as fee + return tokens[tokenAddress][feeAccount]; + } + + function withdrawOwnerCommissoinEther() public returns (string memory){ + require(msg.sender == feeAccount, 'Invalid caller'); + uint256 amount = availableOwnerCommissionEther(); + require (amount > 0, 'Nothing to withdraw'); + tokens[address(0)][feeAccount] = 0; + msg.sender.transfer(amount); + emit OwnerWithdrawCommission(msg.sender, address(0), amount); + return "Ether withdrawn successfully"; + } + + function withdrawOwnerCommissoinToken(address tokenAddress) public returns (string memory){ + require(msg.sender == feeAccount, 'Invalid caller'); + uint256 amount = availableOwnerCommissionToken(tokenAddress); + require (amount > 0, 'Nothing to withdraw'); + tokens[tokenAddress][feeAccount] = 0; + ERC20Essential(tokenAddress).transfer(msg.sender, amount); + emit OwnerWithdrawCommission(msg.sender, tokenAddress, amount); + return "Token withdrawn successfully"; + } + + function deposit() public payable { + tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].add(msg.value); + emit Deposit(now, address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]); + } + + function withdraw(uint amount) public { + require(!safeGuard,"System Paused by Admin"); + require(tokens[address(0)][msg.sender] >= amount, 'Not enough balance'); + tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].sub(amount); + msg.sender.transfer(amount); + emit Withdraw(now, address(0), msg.sender, amount, tokens[address(0)][msg.sender]); + } + + function depositToken(address token, uint amount) public { + //remember to call Token(address).approve(address(this), amount) or this contract will not be able to do the transfer on your behalf. + require(token!=address(0), 'Invalid token address'); + require(ERC20Essential(token).transferFrom(msg.sender, address(this), amount), 'tokens could not be transferred'); + tokens[token][msg.sender] = tokens[token][msg.sender].add(amount); + emit Deposit(now, token, msg.sender, amount, tokens[token][msg.sender]); + } + + function withdrawToken(address token, uint amount) public { + require(!safeGuard,"System Paused by Admin"); + require(token!=address(0), 'Invalid token address'); + require(tokens[token][msg.sender] >= amount, 'not enough token balance'); + tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount); + ERC20Essential(token).transfer(msg.sender, amount); + emit Withdraw(now, token, msg.sender, amount, tokens[token][msg.sender]); + } + + function balanceOf(address token, address user) public view returns (uint) { + return tokens[token][user]; + } + + function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires) public { + bytes32 hash = keccak256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires)); + orders[msg.sender][hash] = true; + emit Order(now, tokenGet, amountGet, tokenGive, amountGive, expires, msg.sender); + } + + + /* address[4] addressArray elements + 0 = tokenGet + 1 = tokenGive + 2 = tradeMaker + 3 = referrer + */ + function trade(address[4] memory addressArray, uint amountGet, uint amountGive, uint expires, uint8 v, bytes32 r, bytes32 s, uint amount, uint orderBookID) public { + require(!safeGuard,"System Paused by Admin"); + //amount is in amountGet terms + bytes32 hash = keccak256(abi.encodePacked(address(this), addressArray[0], amountGet, addressArray[1], amountGive, expires)); + require(orders[addressArray[2]][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == addressArray[2], 'Invalid trade parameters'); + require(block.number <= expires, 'Trade is expired'); + require(orderFills[addressArray[2]][hash].add(amount) <= amountGet, 'Trade order is filled'); + + tradeBalances(addressArray, amountGet, amountGive, amount ); + orderFills[addressArray[2]][hash] = orderFills[addressArray[2]][hash].add(amount); + + emit Trade(now, addressArray[0], amount, addressArray[1], amountGive * amount / amountGet, addressArray[2], msg.sender, orderBookID); + } + + /** + addressArray array elements + 0 = tokenGet + 1 = tokenGive + 2 = user + 3 = referrer + */ + function tradeBalances(address[4] memory addressArray, uint amountGet, uint amountGive, uint amount) internal { + + uint tradingFeeXfer = calculatePercentage(amount,tradingFee); + + //processing referrers bonus - which is % of the trading fee + processReferrerBonus(addressArray[3], tradingFeeXfer); + + tokens[addressArray[0]][msg.sender] = tokens[addressArray[0]][msg.sender].sub(amount.add(tradingFeeXfer)); + tokens[addressArray[0]][addressArray[2]] = tokens[addressArray[0]][addressArray[2]].add(amount); + tokens[addressArray[0]][feeAccount] = tokens[addressArray[0]][feeAccount].add(tradingFeeXfer); + + tokens[addressArray[1]][addressArray[2]] = tokens[addressArray[1]][addressArray[2]].sub(amountGive.mul(amount) / amountGet); + tokens[addressArray[1]][msg.sender] = tokens[addressArray[1]][msg.sender].add(amountGive.mul(amount) / amountGet); + } + + + + function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public view returns(bool) { + + if (!( + tokens[tokenGet][sender] >= amount && + availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, user, v, r, s) >= amount + )) return false; + return true; + } + + function testVRS(address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint8 v, bytes32 r, bytes32 s ) public view returns(address){ + + bytes32 hash = keccak256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires)); + + return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s); + + } + + function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, address user, uint8 v, bytes32 r, bytes32 s) public view returns(uint) { + bytes32 hash = keccak256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires)); + uint available1; + if (!( + (orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),v,r,s) == user) && + block.number <= expires + )) return 0; + available1 = tokens[tokenGive][user].mul(amountGet) / amountGive; + + if (amountGet.sub(orderFills[user][hash]) 0, 'Insufficient referrer bonus'); + referrerBonusBalance[msgSender] = 0; + + + //transfer the referrer bonus + msgSender.transfer(referralBonus); + + //fire event + emit ReferrerBonusWithdrawn(msgSender, referralBonus); + + return true; + } + + + + + + + + +} diff --git a/DEX/TronDex.sol b/DEX/TronDex.sol new file mode 100644 index 0000000..e77ca13 --- /dev/null +++ b/DEX/TronDex.sol @@ -0,0 +1,518 @@ +pragma solidity 0.5.8; /* + + + + + ___________________________________________________________________ + _ _ ______ + | | / / / + --|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) + __/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + + + ████████╗██████╗ ██████╗ ███╗ ██╗ ██████╗ ███████╗██╗ ██╗ + ╚══██╔══╝██╔══██╗██╔═══██╗████╗ ██║ ██╔══██╗██╔════╝╚██╗██╔╝ + ██║ ██████╔╝██║ ██║██╔██╗ ██║ ██║ ██║█████╗ ╚███╔╝ + ██║ ██╔══██╗██║ ██║██║╚██╗██║ ██║ ██║██╔══╝ ██╔██╗ + ██║ ██║ ██║╚██████╔╝██║ ╚████║ ██████╔╝███████╗██╔╝ ██╗ + ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ + + + + + +------------------------------------------------------------------------------------------------------ + Copyright (c) 2019 Onwards TRON DEX Inc. ( https://xxxxxxxx.io ) + Contract designed with ❤ by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------------------------------------------ +*/ + + +//******************************************************************* +//------------------------ SafeMath Library ------------------------- +//******************************************************************* +library SafeMath { + /** + * @dev Returns the addition of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `+` operator. + * + * Requirements: + * - Addition cannot overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, "SafeMath: addition overflow"); + + return c; + } + + /** + * @dev Returns the subtraction of two unsigned integers, reverting on + * overflow (when the result is negative). + * + * Counterpart to Solidity's `-` operator. + * + * Requirements: + * - Subtraction cannot overflow. + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, "SafeMath: subtraction overflow"); + uint256 c = a - b; + + return c; + } + + /** + * @dev Returns the multiplication of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `*` operator. + * + * Requirements: + * - Multiplication cannot overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + // Gas optimization: this is cheaper than requiring 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 + if (a == 0) { + return 0; + } + + uint256 c = a * b; + require(c / a == b, "SafeMath: multiplication overflow"); + + return c; + } + + /** + * @dev Returns the integer division of two unsigned integers. Reverts on + * division by zero. The result is rounded towards zero. + * + * Counterpart to Solidity's `/` operator. Note: this function uses a + * `revert` opcode (which leaves remaining gas untouched) while Solidity + * uses an invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // Solidity only automatically asserts when dividing by 0 + require(b > 0, "SafeMath: division by zero"); + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + + return c; + } + + /** + * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), + * Reverts when dividing by zero. + * + * Counterpart to Solidity's `%` operator. This function uses a `revert` + * opcode (which leaves remaining gas untouched) while Solidity uses an + * invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + require(b != 0, "SafeMath: modulo by zero"); + return a % b; + } +} + + +interface ERC20Essential +{ + + function transfer(address _to, uint256 _amount) external returns (bool); + function transferFrom(address _from, address _to, uint256 _amount) external returns (bool); + +} + + + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address public owner; + address private newOwner; + + + event OwnershipTransferred(uint256 curTime, address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner, 'Only owner can call this function'); + _; + } + + + function onlyOwnerTransferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner, 'Only new owner can call this function'); + emit OwnershipTransferred(now, owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +contract TronDEX is owned { + using SafeMath for uint256; + bool public safeGuard; // To hault all non owner functions in case of imergency - by default false + address public feeAccount; //the account that will receive fees + uint32 public tradingFeeTradeMaker = 300; // 300 = 0.3% + uint32 public tradingFeeTradeTaker = 300; // 300 = 0.3% + + //referrals + uint256 public refPercent = 10; // percent to calculate referal bonous - by default 10% of trading fee + + mapping (address => mapping (address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether) + mapping (address => mapping (bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature) + mapping (address => mapping (bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled) + + /* Mapping to track referrer. The second address is the address of referrer, the Up-line/ Sponsor */ + mapping (address => address) public referrers; + /* Mapping to track referrer bonus for all the referrers */ + mapping (address => uint) public referrerBonusBalance; + + event Order(uint256 curTime, address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, address user); + event Cancel(uint256 curTime, address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, address user, uint8 v, bytes32 r, bytes32 s); + event Trade( uint256 curTime, address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give, uint256 orderBookID); + event DepositTRC20(uint256 curTime, address token, address user, uint amount, uint balance); + event DepositTRC10(uint256 curTime, uint64 token, address user, uint amount, uint balance); + event DepositTRX(uint256 curTime, address user, uint amount, uint balance); + event WithdrawTRC20(uint256 curTime, address token, address user, uint amount, uint balance); + event WithdrawTRC10(uint256 curTime, uint64 token, address user, uint amount, uint balance); + event WithdrawTRX(uint256 curTime, address user, uint amount, uint balance); + event OwnerWithdrawCommissionTRC20(address indexed owner, address indexed tokenAddress, uint256 amount); + event OwnerWithdrawCommissionTRC10(address indexed owner, uint64 indexed tokenID, uint256 amount); + // Events to track ether transfer to referrers + event ReferrerBonus(address indexed referer, address indexed trader, uint256 referralBonus, uint256 timestamp ); + event ReferrerBonusWithdrawn(address indexed referrer, uint256 indexed amount); + + + + constructor() public { + feeAccount = msg.sender; + } + + function changeSafeguardStatus() onlyOwner public + { + if (safeGuard == false) + { + safeGuard = true; + } + else + { + safeGuard = false; + } + } + + //Calculate percent and return result + function calculatePercentage(uint256 PercentOf, uint256 percentTo ) internal pure returns (uint256) + { + uint256 factor = 100000; //so to make 1000 = 1% + require(percentTo <= factor, 'percentTo must be less than factor'); + uint256 c = PercentOf.mul(percentTo).div(factor); + return c; + } + + + + + // contract accepts incoming ether - this needed in case owner want to fund refPool + function() payable external { } + + + function changeFeeAccount(address feeAccount_) public onlyOwner { + feeAccount = feeAccount_; + } + + function changetradingFee(uint32 tradingFeeTradeMaker_, uint32 tradingFeeTradeTaker_) public onlyOwner{ + require(tradingFeeTradeMaker_ <= 10000 && tradingFeeTradeTaker_ <= 10000, 'trading fee can not be more than 100%'); + tradingFeeTradeMaker = tradingFeeTradeMaker_; + tradingFeeTradeTaker = tradingFeeTradeTaker_; + } + + function availableOwnerCommissionTRC10(uint64 tokenID) public view returns(uint256){ + //tokenID = 0 is for TRX + return tokens[address(tokenID)][feeAccount]; + } + + function availableOwnerCommissionTRC20(address tokenAddress) public view returns(uint256){ + //assress 0x0 only holds ether as fee + return tokens[tokenAddress][feeAccount]; + } + + //tokenID = 0 is for TRX + function withdrawOwnerCommissoinTRC10(uint64 tokenID) public returns (string memory){ + require(msg.sender == feeAccount, 'Invalid caller'); + uint256 amount = availableOwnerCommissionTRC10(tokenID); + require (amount > 0, 'Nothing to withdraw'); + tokens[address(tokenID)][feeAccount] = 0; + if(tokenID==0){ + msg.sender.transfer(amount); + } + else{ + msg.sender.transferToken(amount, tokenID); + } + + emit OwnerWithdrawCommissionTRC10(msg.sender, tokenID, amount); + return "TRC10 tokens withdrawn successfully"; + } + + function withdrawOwnerCommissoinTRC20(address tokenAddress) public returns (string memory){ + require(msg.sender == feeAccount, 'Invalid caller'); + uint256 amount = availableOwnerCommissionTRC20(tokenAddress); + require (amount > 0, 'Nothing to withdraw'); + tokens[tokenAddress][feeAccount] = 0; + ERC20Essential(tokenAddress).transfer(msg.sender, amount); + emit OwnerWithdrawCommissionTRC20(msg.sender, tokenAddress, amount); + return "TRC20 tokens withdrawn successfully"; + } + + function depositTRX() public payable { + tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].add(msg.value); + emit DepositTRX(now, msg.sender, msg.value, tokens[address(0)][msg.sender]); + } + + function depositTRC10() public payable { + uint64 tokenID = uint64(msg.tokenid); + tokens[address(tokenID)][msg.sender] = tokens[address(tokenID)][msg.sender].add(msg.tokenvalue); + emit DepositTRC10(now, tokenID, msg.sender, msg.tokenvalue, tokens[address(tokenID)][msg.sender]); + + } + + function depositTRC20(address token, uint amount) public { + //remember to call Token(address).approve(address(this), amount) or this contract will not be able to do the transfer on your behalf. + require(token!=address(0), 'Invalid token address'); + require(ERC20Essential(token).transferFrom(msg.sender, address(this), amount), 'tokens could not be transferred'); + tokens[token][msg.sender] = tokens[token][msg.sender].add(amount); + emit DepositTRC20(now, token, msg.sender, amount, tokens[token][msg.sender]); + } + + + function withdrawTRX(uint amount) public { + require(!safeGuard,"System Paused by Admin"); + require(tokens[address(0)][msg.sender] >= amount, 'Not enough balance'); + tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].sub(amount); + msg.sender.transfer(amount); + emit WithdrawTRX(now, msg.sender, amount, tokens[address(0)][msg.sender]); + } + + function withdrawTRC10(uint64 tokenID, uint amount) public { + require(!safeGuard,"System Paused by Admin"); + require(tokens[address(tokenID)][msg.sender] >= amount, 'Not enough balance'); + tokens[address(tokenID)][msg.sender] = tokens[address(tokenID)][msg.sender].sub(amount); + msg.sender.transferToken(amount, tokenID); + emit WithdrawTRC10(now, tokenID, msg.sender, amount, tokens[address(tokenID)][msg.sender]); + } + + + function withdrawTRC20(address token, uint amount) public { + require(!safeGuard,"System Paused by Admin"); + require(token!=address(0), 'Invalid token address'); + require(tokens[token][msg.sender] >= amount, 'not enough token balance'); + tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount); + ERC20Essential(token).transfer(msg.sender, amount); + emit WithdrawTRC20(now, token, msg.sender, amount, tokens[token][msg.sender]); + } + + function balanceOfTRC20(address token, address user) public view returns (uint) { + return tokens[token][user]; + } + + function balanceOfTRC10(uint64 token, address user) public view returns (uint) { + return tokens[address(token)][user]; + } + + function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires) public { + bytes32 hash = keccak256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires)); + orders[msg.sender][hash] = true; + emit Order(now, tokenGet, amountGet, tokenGive, amountGive, expires, msg.sender); + } + + + /* address[4] addressArray elements + 0 = tokenGet + 1 = tokenGive + 2 = tradeMaker + 3 = referrer + */ + function trade(address[4] memory addressArray, uint amountGet, uint amountGive, uint expires, uint8 v, bytes32 r, bytes32 s, uint amount, uint orderBookID) public { + require(!safeGuard,"System Paused by Admin"); + //amount is in amountGet terms + bytes32 hash = keccak256(abi.encodePacked(address(this), addressArray[0], amountGet, addressArray[1], amountGive, expires)); + require(orders[addressArray[2]][hash] || ecrecover(keccak256(abi.encodePacked("\x19TRON Signed Message:\n32", hash)),v,r,s) == addressArray[2], 'Invalid trade parameters'); + require(block.number <= expires, 'Trade is expired'); + require(orderFills[addressArray[2]][hash].add(amount) <= amountGet, 'Trade order is filled'); + + tradeBalances(addressArray, amountGet, amountGive, amount ); + orderFills[addressArray[2]][hash] = orderFills[addressArray[2]][hash].add(amount); + + emit Trade(now, addressArray[0], amount, addressArray[1], amountGive * amount / amountGet, addressArray[2], msg.sender, orderBookID); + } + + + /** + addressArray array elements + 0 = tokenGet + 1 = tokenGive + 2 = user + 3 = referrer + */ + function tradeBalances(address[4] memory addressArray, uint amountGet, uint amountGive, uint amount) internal { + + uint tradingFeeXfer = calculatePercentage(amount,tradingFeeTradeMaker); + + //processing referrers bonus - which is % of the trading fee + processReferrerBonus(addressArray[3], tradingFeeXfer); + + tokens[addressArray[0]][msg.sender] = tokens[addressArray[0]][msg.sender].sub(amount.add(tradingFeeXfer)); + tokens[addressArray[0]][addressArray[2]] = tokens[addressArray[0]][addressArray[2]].add(amount); + tokens[addressArray[0]][feeAccount] = tokens[addressArray[0]][feeAccount].add(tradingFeeXfer); + + tokens[addressArray[1]][addressArray[2]] = tokens[addressArray[1]][addressArray[2]].sub(amountGive.mul(amount) / amountGet); + tokens[addressArray[1]][msg.sender] = tokens[addressArray[1]][msg.sender].add(amountGive.mul(amount) / amountGet); + } + + + + function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public view returns(bool) { + + if (!( + tokens[tokenGet][sender] >= amount && + availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, user, v, r, s) >= amount + )) return false; + return true; + } + + function testVRS(address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint8 v, bytes32 r, bytes32 s ) public view returns(address){ + + bytes32 hash = keccak256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires)); + + return ecrecover(keccak256(abi.encodePacked("\x19TRON Signed Message:\n32", hash)),v,r,s); + + } + + + function getHash(address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires) public view returns(bytes32){ + + return keccak256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires)); + } + + function addressToTokenId(address tokenAddress) public pure returns(uint64){ + return uint64(tokenAddress); + } + + function tokenIdToAddress(uint tokenID) public pure returns(address){ + return address(tokenID); + } + + function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, address user, uint8 v, bytes32 r, bytes32 s) public view returns(uint) { + bytes32 hash = keccak256(abi.encodePacked(address(this), tokenGet, amountGet, tokenGive, amountGive, expires)); + uint available1; + if (!( + (orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19TRON Signed Message:\n32", hash)),v,r,s) == user) && + block.number <= expires + )) return 0; + available1 = tokens[tokenGive][user].mul(amountGet) / amountGive; + + if (amountGet.sub(orderFills[user][hash]) 0, 'Insufficient referrer bonus'); + referrerBonusBalance[msgSender] = 0; + + + //transfer the referrer bonus + msgSender.transfer(referralBonus); + + //fire event + emit ReferrerBonusWithdrawn(msgSender, referralBonus); + + return true; + } + + + + + + + + +} diff --git a/ERC1155 Tokens/PIZ TOKEN.sol b/ERC1155 Tokens/PIZ TOKEN.sol new file mode 100644 index 0000000..8330823 --- /dev/null +++ b/ERC1155 Tokens/PIZ TOKEN.sol @@ -0,0 +1,553 @@ +pragma solidity 0.5.2; + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } +} + + + +/** + * @title ERC165 + * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md + */ +interface ERC165 { + + /** + * @notice Query if a contract implements an interface + * @param _interfaceId The interface identifier, as specified in ERC-165 + * @dev Interface identification is specified in ERC-165. This function + * uses less than 30,000 gas. + */ + function supportsInterface(bytes4 _interfaceId) + external + view + returns (bool); +} + +/** + @title ERC-1155 Multi Token Standard + @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md + Note: The ERC-165 identifier for this interface is 0xd9b67a26. + */ +interface IERC1155 /* is ERC165 */ { + /** + @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero value transfers as well as minting or burning. + Operator will always be msg.sender. + Either event from address `0x0` signifies a minting operation. + An event to address `0x0` signifies a burning or melting operation. + The total value transferred from address 0x0 minus the total value transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID. + To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`. + */ + event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); + + /** + @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero value transfers as well as minting or burning. + Operator will always be msg.sender. + Either event from address `0x0` signifies a minting operation. + An event to address `0x0` signifies a burning or melting operation. + The total value transferred from address 0x0 minus the total value transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID. + To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`. + */ + event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); + + /** + @dev MUST emit when an approval is updated. + */ + event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); + + /** + @dev MUST emit when the URI is updated for a token ID. + URIs are defined in RFC 3986. + The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema". + */ + event URI(string _value, uint256 indexed _id); + + /** + @notice Transfers value amount of an _id from the _from address to the _to address specified. + @dev MUST emit TransferSingle event on success. + Caller must be approved to manage the _from account's tokens (see isApprovedForAll). + MUST throw if `_to` is the zero address. + MUST throw if balance of sender for token `_id` is lower than the `_value` sent. + MUST throw on any other error. + When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return value is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. + @param _from Source address + @param _to Target address + @param _id ID of the token type + @param _value Transfer amount + @param _data Additional data with no specified format, sent in call to `_to` + */ + function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; + + /** + @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). + @dev MUST emit TransferBatch event on success. + Caller must be approved to manage the _from account's tokens (see isApprovedForAll). + MUST throw if `_to` is the zero address. + MUST throw if length of `_ids` is not the same as length of `_values`. + MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. + MUST throw on any other error. + When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. + @param _from Source addresses + @param _to Target addresses + @param _ids IDs of each token type + @param _values Transfer amounts per token type + @param _data Additional data with no specified format, sent in call to `_to` + */ + function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; + + /** + @notice Get the balance of an account's Tokens. + @param _owner The address of the token holder + @param _id ID of the Token + @return The _owner's balance of the Token type requested + */ + function balanceOf(address _owner, uint256 _id) external view returns (uint256); + + /** + @notice Get the balance of multiple account/token pairs + @param _owners The addresses of the token holders + @param _ids ID of the Tokens + @return The _owner's balance of the Token types requested + */ + function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); + + /** + @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. + @dev MUST emit the ApprovalForAll event on success. + @param _operator Address to add to the set of authorized operators + @param _approved True if the operator is approved, false to revoke approval + */ + function setApprovalForAll(address _operator, bool _approved) external; + + /** + @notice Queries the approval status of an operator for a given owner. + @param _owner The owner of the Tokens + @param _operator Address of authorized operator + @return True if the operator is approved, false if not + */ + function isApprovedForAll(address _owner, address _operator) external view returns (bool); +} + +interface IERC1155TokenReceiver { + /** + @notice Handle the receipt of a single ERC1155 token type + @dev The smart contract calls this function on the recipient + after a `safeTransferFrom`. This function MAY throw to revert and reject the + transfer. Return of other than the magic value MUST result in the + transaction being reverted + Note: the contract address is always the message sender + @param _operator The address which called `safeTransferFrom` function + @param _from The address which previously owned the token + @param _id An array containing the ids of the token being transferred + @param _value An array containing the amount of tokens being transferred + @param _data Additional data with no specified format + @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` + */ + function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); + + /** + @notice Handle the receipt of multiple ERC1155 token types + @dev The smart contract calls this function on the recipient + after a `safeTransferFrom`. This function MAY throw to revert and reject the + transfer. Return of other than the magic value MUST result in the + transaction being reverted + Note: the contract address is always the message sender + @param _operator The address which called `safeTransferFrom` function + @param _from The address which previously owned the token + @param _ids An array containing ids of each token being transferred + @param _values An array containing amounts of each token being transferred + @param _data Additional data with no specified format + @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` + */ + function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); +} + + + +/** + * Utility library of inline functions on addresses + */ +library Address { + + /** + * Returns whether the target address is a contract + * @dev This function will return false if invoked during the constructor of a contract, + * as the code is not actually created until after the constructor finishes. + * @param account address of the account to check + * @return whether the target address is a contract + */ + function isContract(address account) internal view returns (bool) { + uint256 size; + // XXX Currently there is no better way to check if there is a contract in an address + // than to check the size of the code at that address. + // See https://ethereum.stackexchange.com/a/14016/36603 + // for more details about how this works. + // TODO Check this again before the Serenity release, because all addresses will be + // contracts then. + // solium-disable-next-line security/no-inline-assembly + assembly { size := extcodesize(account) } + return size > 0; + } + +} + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { + // Gas optimization: this is cheaper than asserting 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 + if (a == 0) { + return 0; + } + + c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + // uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return a / b; + } + + /** + * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256 c) { + c = a + b; + assert(c >= a); + return c; + } +} + +// A sample implementation of core ERC1155 function. +contract ERC1155 is IERC1155, ERC165 +{ + using SafeMath for uint256; + using Address for address; + + bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61; + bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81; + + // id => (owner => balance) + mapping (uint256 => mapping(address => uint256)) internal balances; + + // owner => (operator => approved) + mapping (address => mapping(address => bool)) internal operatorApproval; + + /* elements of ERC865 transfers */ + mapping(bytes32 => bool) transactionHashes; + event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); + event ApprovalPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); + + +/////////////////////////////////////////// ERC165 ////////////////////////////////////////////// + + /* + bytes4(keccak256('supportsInterface(bytes4)')); + */ + bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; + + /* + bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ + bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ + bytes4(keccak256("balanceOf(address,uint256)")) ^ + bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ + bytes4(keccak256("setApprovalForAll(address,bool)")) ^ + bytes4(keccak256("isApprovedForAll(address,address)")); + */ + bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; + + function supportsInterface(bytes4 _interfaceId) + public + view + returns (bool) { + if (_interfaceId == INTERFACE_SIGNATURE_ERC165 || + _interfaceId == INTERFACE_SIGNATURE_ERC1155) { + return true; + } + + return false; + } + +/////////////////////////////////////////// ERC1155 ////////////////////////////////////////////// + + + function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external { + + require(_to != address(0x0), "_to must be non-zero."); + require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); + + // SafeMath will throw with insuficient funds _from + // or if _id is not valid (balance will be 0) + balances[_id][_from] = balances[_id][_from].sub(_value); + balances[_id][_to] = _value.add(balances[_id][_to]); + + emit TransferSingle(msg.sender, _from, _to, _id, _value); + + if (_to.isContract()) { + require(IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _value, _data) == ERC1155_RECEIVED, "Receiver contract did not accept the transfer."); + } + } + + /** + @notice Transfers value amount of an _id from the _from address to the _to addresses specified. Each parameter array should be the same length, with each index correlating. + @dev MUST emit TransferSingle event on success. + Caller must be approved to manage the _from account's tokens (see isApprovedForAll). + MUST Throw if `_to` is the zero address. + MUST Throw if `_id` is not a valid token ID. + MUST Throw on any other error. + When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return value is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. + @param _from Source addresses + @param _to Target addresses + @param _id ID of the token type + @param _value Transfer amount + @param _data Additional data with no specified format, sent in call to `_to` + */ + function safeTransferFromERC865(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data, uint256 _fee, uint256 _nonce, uint8 v, bytes32 r, bytes32 s) external { + + require(_to != address(0x0), "_to must be non-zero."); + //require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); + + // ERC865 implementation + bytes32 hashedTx = processSenderData('safeTransferFromERC865', _from, _to, _id, _value, _fee, _nonce, v, r, s); + + // SafeMath will throw with insuficient funds _from, or if _id is not valid (balance will be 0) + //balances[_id][_from] = balances[_id][_from].sub(_value); + balances[_id][_to] = balances[_id][_to].add(_value); + balances[_id][msg.sender] = balances[_id][msg.sender].add(_fee); + + transactionHashes[hashedTx] = true; + emit TransferSingle(msg.sender, _from, _to, _id, _value); + + if (_to.isContract()) { + require(IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _value, _data) == ERC1155_RECEIVED, "Receiver contract did not accept the transfer."); + } + } + + function processSenderData(string memory functionIdentifier,address _from, address _to, uint256 _id, uint256 _value, uint256 _fee, uint256 _nonce, uint8 v, bytes32 r, bytes32 s) internal view returns(bytes32) { + bytes32 hashedTx = keccak256(abi.encodePacked(functionIdentifier, address(this), _from, _to, _id, _value, _fee, _nonce)); + require(transactionHashes[hashedTx] == false, 'transaction hash is already used'); + address calculatedFrom = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedTx)),v,r,s); + require(calculatedFrom == _from, 'Invalid _from address'); + return hashedTx; + } + + /** + @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). + @dev MUST emit TransferBatch event on success. + Caller must be approved to manage the _from account's tokens (see isApprovedForAll). + MUST Throw if `_to` is the zero address. + MUST Throw if any of the `_ids` is not a valid token ID. + MUST Throw on any other error. + When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. + @param _from Source address + @param _to Target address + @param _ids IDs of each token type + @param _values Transfer amounts per token type + @param _data Additional data with no specified format, sent in call to `_to` + */ + function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external { + + // MUST Throw on errors + require(_to != address(0x0), "destination address must be non-zero."); + require(_ids.length == _values.length, "_ids and _values array lenght must match."); + require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); + + for (uint256 i = 0; i < _ids.length; ++i) { + uint256 id = _ids[i]; + uint256 value = _values[i]; + + // SafeMath will throw with insuficient funds _from + // or if _id is not valid (balance will be 0) + balances[id][_from] = balances[id][_from].sub(value); + balances[id][_to] = value.add(balances[id][_to]); + } + + // MUST emit event + emit TransferBatch(msg.sender, _from, _to, _ids, _values); + + // Now that the balances are updated, + // call onERC1155BatchReceived if the destination is a contract + if (_to.isContract()) { + require(IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _values, _data) == ERC1155_BATCH_RECEIVED, "Receiver contract did not accept the transfer."); + } + } + + /** + @notice Get the balance of an account's Tokens. + @param _owner The address of the token holder + @param _id ID of the Token + @return The _owner's balance of the Token type requested + */ + function balanceOf(address _owner, uint256 _id) external view returns (uint256) { + // The balance of any account can be calculated from the Transfer events history. + // However, since we need to keep the balances to validate transfer request, + // there is no extra cost to also privide a querry function. + return balances[_id][_owner]; + } + + + /** + @notice Get the balance of multiple account/token pairs + @param _owners The addresses of the token holders + @param _ids ID of the Tokens + @return The _owner's balance of the Token types requested + */ + function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) { + + require(_owners.length == _ids.length); + + uint256[] memory balances_ = new uint256[](_owners.length); + + for (uint256 i = 0; i < _owners.length; ++i) { + balances_[i] = balances[_ids[i]][_owners[i]]; + } + + return balances_; + } + + /** + @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. + @dev MUST emit the ApprovalForAll event on success. + @param _operator Address to add to the set of authorized operators + @param _approved True if the operator is approved, false to revoke approval + */ + function setApprovalForAll(address _operator, bool _approved) external { + operatorApproval[msg.sender][_operator] = _approved; + emit ApprovalForAll(msg.sender, _operator, _approved); + } + + /** + @notice Queries the approval status of an operator for a given owner. + @param _owner The owner of the Tokens + @param _operator Address of authorized operator + @return True if the operator is approved, false if not + */ + function isApprovedForAll(address _owner, address _operator) external view returns (bool) { + return operatorApproval[_owner][_operator]; + } +} + + +//================================================================================================// +//= MAIN MINTABLE ERC1155 CONTRACT =// +//================================================================================================// + +/** + @dev Mintable form of ERC1155 + Shows how easy it is to mint new items. +*/ +contract MainPizERC1155 is ERC1155, owned { + + bytes4 constant private INTERFACE_SIGNATURE_URI = 0x0e89341c; + + + + // id => creators + mapping (uint256 => address) public creators; + + // A nonce to ensure we have a unique id each time we mint. + uint256 public nonce; + + modifier creatorOnly(uint256 _id) { + require(creators[_id] == msg.sender); + _; + } + + function supportsInterface(bytes4 _interfaceId) + public + view + returns (bool) { + if (_interfaceId == INTERFACE_SIGNATURE_URI) { + return true; + } else { + return super.supportsInterface(_interfaceId); + } + } + + // Creates a new token type and assings _initialSupply to minter + function create(uint256 _initialSupply, string calldata _uri) external returns(uint256 _id) { + + _id = ++nonce; + creators[_id] = msg.sender; + balances[_id][msg.sender] = _initialSupply; + + // Transfer event with mint semantic + emit TransferSingle(msg.sender, address(0x0), msg.sender, _id, _initialSupply); + + if (bytes(_uri).length > 0) + emit URI(_uri, _id); + } + + // Burn tokens by owner of the tokens + function burn(uint256 _id, uint256 _quantities){ + // Burn/substract the items from the caller. Integer Inderflow is managed by SafeMath + balances[_id][to] = quantity.add(balances[_id][to]); + } + + // Batch mint tokens. Assign directly to _to[]. + function mint(uint256 _id, address[] calldata _to, uint256[] calldata _quantities) external creatorOnly(_id) { + + for (uint256 i = 0; i < _to.length; ++i) { + + address to = _to[i]; + uint256 quantity = _quantities[i]; + + // Grant the items to the caller + balances[_id][to] = quantity.add(balances[_id][to]); + + // Emit the Transfer/Mint event. + // the 0x0 source address implies a mint + // It will also provide the circulating supply info. + emit TransferSingle(msg.sender, address(0x0), to, _id, quantity); + + if (to.isContract()) { + require(IERC1155TokenReceiver(to).onERC1155Received(msg.sender, msg.sender, _id, quantity, '') == ERC1155_RECEIVED, "Receiver contract did not accept the transfer."); + } + } + } + + function setURI(string calldata _uri, uint256 _id) external creatorOnly(_id) { + emit URI(_uri, _id); + } +} diff --git a/ERC20 Tokens/Alteredux.sol b/ERC20 Tokens/Alteredux.sol new file mode 100644 index 0000000..e746966 --- /dev/null +++ b/ERC20 Tokens/Alteredux.sol @@ -0,0 +1,456 @@ +/** + *Submitted for verification at Etherscan.io on 2020-02-07 +*/ + +pragma solidity 0.5.16; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + █████╗ ██╗ ████████╗███████╗██████╗ ███████╗██████╗ ██╗ ██╗██╗ ██╗ +██╔══██╗██║ ╚══██╔══╝██╔════╝██╔══██╗██╔════╝██╔══██╗██║ ██║╚██╗██╔╝ +███████║██║ ██║ █████╗ ██████╔╝█████╗ ██║ ██║██║ ██║ ╚███╔╝ +██╔══██║██║ ██║ ██╔══╝ ██╔══██╗██╔══╝ ██║ ██║██║ ██║ ██╔██╗ +██║ ██║███████╗██║ ███████╗██║ ██║███████╗██████╔╝╚██████╔╝██╔╝ ██╗ +╚═╝ ╚═╝╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ ╚═════╝ ╚═╝ ╚═╝ + + + + +=== 'Alteredux' Token contract with following features === + => ERC20 Compliance + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => Burnable and minting + => user whitelisting + => air drop (active) + + +======================= Quick Stats =================== + => Name : Alteredux + => Symbol : AEX + => Total supply: 10,000,000,000 (10 Billion) + => Decimals : 18 + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + => Community Audit by Bug Bounty program + + +------------------------------------------------------------------- + Copyright (c) 2020 onwards Alteredux Inc. ( https://Alteredux.com ) + Contract designed with ❤ by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + + + + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + address payable internal newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + emit OwnershipTransferred(address(0), owner); + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +//****************************************************************************// +//--------------------- MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract Alteredux is owned { + + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string constant private _name = "Alteredux"; + string constant private _symbol = "AEX"; + uint256 constant private _decimals = 18; + uint256 private _totalSupply = 10000000000 * (10**_decimals); //10 Billion tokens + uint256 constant public maxSupply = 10000000000 * (10**_decimals); //10 Billion tokens + bool public safeguard; //putting safeguard on will halt all non-owner functions + + // This creates a mapping with all data storage + mapping (address => uint256) private _balanceOf; + mapping (address => mapping (address => uint256)) private _allowance; + mapping (address => bool) public frozenAccount; + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenAccounts(address target, bool frozen); + + // This will log approval of token Transfer + event Approval(address indexed from, address indexed spender, uint256 value); + + + + /*====================================== + = STANDARD ERC20 FUNCTIONS = + ======================================*/ + + /** + * Returns name of token + */ + function name() public pure returns(string memory){ + return _name; + } + + /** + * Returns symbol of token + */ + function symbol() public pure returns(string memory){ + return _symbol; + } + + /** + * Returns decimals of token + */ + function decimals() public pure returns(uint256){ + return _decimals; + } + + /** + * Returns totalSupply of token. + */ + function totalSupply() public view returns (uint256) { + return _totalSupply; + } + + /** + * Returns balance of token + */ + function balanceOf(address user) public view returns(uint256){ + return _balanceOf[user]; + } + + /** + * Returns allowance of token + */ + function allowance(address owner, address spender) public view returns (uint256) { + return _allowance[owner][spender]; + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguard); + require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + // overflow and undeflow checked by SafeMath Library + _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender + _balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + //checking of allowance and token value is done by SafeMath + _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + /* AUDITOR NOTE: + Many dex and dapps pre-approve large amount of tokens to save gas for subsequent transaction. This is good use case. + On flip-side, some malicious dapp, may pre-approve large amount and then drain all token balance from user. + So following condition is kept in commented. It can be be kept that way or not based on client's consent. + */ + //require(_balanceOf[msg.sender] >= _value, "Balance does not have enough tokens"); + _allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + /** + * @dev Increase the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To increment + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * Emits an Approval event. + * @param spender The address which will spend the funds. + * @param value The amount of tokens to increase the allowance by. + */ + function increase_allowance(address spender, uint256 value) public returns (bool) { + require(spender != address(0)); + _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(value); + emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); + return true; + } + + /** + * @dev Decrease the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To decrement + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * Emits an Approval event. + * @param spender The address which will spend the funds. + * @param value The amount of tokens to decrease the allowance by. + */ + function decrease_allowance(address spender, uint256 value) public returns (bool) { + require(spender != address(0)); + _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(value); + emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); + return true; + } + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + constructor() public{ + //sending all the tokens to Owner + _balanceOf[owner] = _totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, _totalSupply); + } + + //It just accepts ETH + function () external payable { + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of enough token balance is done by SafeMath + _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); // Subtract from the sender + _totalSupply = _totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of allowance and token value is done by SafeMath + _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the targeted balance + _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + _totalSupply = _totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + emit Transfer(_from, address(0), _value); + return true; + } + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenAccounts(target, freeze); + } + + /** + * @notice Create `mintedAmount` tokens and send it to `target` + * @param target Address to receive the tokens + * @param mintedAmount the amount of tokens it will receive + */ + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + require(_totalSupply.add(mintedAmount) <= maxSupply, "Cannot Mint more than maximum supply"); + _balanceOf[target] = _balanceOf[target].add(mintedAmount); + _totalSupply = _totalSupply.add(mintedAmount); + emit Transfer(address(0), target, mintedAmount); + } + + + + /** + * Owner can transfer tokens from contract to owner address + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + + /*************************************/ + /* Section for User Air drop */ + /*************************************/ + + /** + * Run an ACTIVE Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public returns(bool) { + uint256 totalAddresses = recipients.length; + require(totalAddresses <= 150,"Too many recipients"); + for(uint i = 0; i < totalAddresses; i++) + { + //This will loop through all the recipients and send them the specified tokens + //Input data validation is unncessary, as that is done by SafeMath and which also saves some gas. + transfer(recipients[i], tokenAmount[i]); + } + return true; + } + + + +} \ No newline at end of file diff --git a/ERC20 Tokens/Azuma Coin.sol b/ERC20 Tokens/Azuma Coin.sol new file mode 100644 index 0000000..9b0a82e --- /dev/null +++ b/ERC20 Tokens/Azuma Coin.sol @@ -0,0 +1,354 @@ +/** + *Submitted for verification at Etherscan.io on 2019-09-09 +*/ + +pragma solidity 0.5.11; /* + + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + + ++ ++ + + + + ++ + ++--++--++ + +--+ +----++---++ + ++ ++ ++ ++-- ++ ++++-- ++ + ++++ +-+ +++++ + ++-+ +-++------+ +-----+ +-+ +-++-+ +-+ +-----+ +-----+ +-++-+ +---+ + + + +=== 'Azumacoin' Token contract with following features === + => ERC20 Compliance + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => Burnable and minting + + +======================= Quick Stats =================== + => Name : Azuma coin + => Symbol : Azum + => Total supply: 500,000,000 (500 Million) + => Decimals : 18 + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + + + +------------------------------------------------------------------- + Copyright (c) 2019 onwards Azuma Coin Inc. ( https://Azumacoin.io ) + Contract designed with ? by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + + + + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + address payable internal newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +//****************************************************************************// +//--------------------- MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract Azumacoin is owned { + + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string constant public name = "Azuma coin"; + string constant public symbol = "AZUM"; + uint256 constant public decimals = 18; + uint256 constant public maxSupply = 500000000 * (10**decimals); //500 million tokens + uint256 public totalSupply; + bool public safeguard; //putting safeguard on will halt all non-owner functions + + + // This creates a mapping with all data storage + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + mapping (address => bool) public frozenAccount; + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenAccounts(address target, bool frozen); + + // This will log approval of token Transfer + event Approval(address indexed from, address indexed spender, uint256 value); + + + + /*====================================== + = STANDARD ERC20 FUNCTIONS = + ======================================*/ + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguard); + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + // overflow and undeflow checked by SafeMath Library + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value, "Balance does not have enough tokens"); + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + constructor() public{ + + totalSupply = maxSupply; + + //sending all the tokens to Owner + balanceOf[owner] = totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, totalSupply); + } + + //just accept incoming ether + function () external payable {} + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of enough token balance is done by SafeMath + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of allowance and token value is done by SafeMath + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + emit Transfer(_from, address(0), _value); + return true; + } + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenAccounts(target, freeze); + } + + /** + * @notice Create `mintedAmount` tokens and send it to `target` + * @param target Address to receive the tokens + * @param mintedAmount the amount of tokens it will receive + */ + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + + //can not mint more than maxSupply + require(totalSupply.add(mintedAmount) < maxSupply, 'can not mint more than maxSupply'); + + balanceOf[target] = balanceOf[target].add(mintedAmount); + totalSupply = totalSupply.add(mintedAmount); + emit Transfer(address(0), target, mintedAmount); + } + + + + /** + * Owner can transfer tokens from contract to owner address + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + +} \ No newline at end of file diff --git a/ERC20 Tokens/CENTI Token.sol b/ERC20 Tokens/CENTI Token.sol new file mode 100644 index 0000000..3e6c985 --- /dev/null +++ b/ERC20 Tokens/CENTI Token.sol @@ -0,0 +1,557 @@ +pragma solidity 0.5.16; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + .----------------. .----------------. .-----------------. .----------------. .----------------. +| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. | +| | ______ | || | _________ | || | ____ _____ | || | _________ | || | _____ | | +| | .' ___ | | || | |_ ___ | | || ||_ \|_ _| | || | | _ _ | | || | |_ _| | | +| | / .' \_| | || | | |_ \_| | || | | \ | | | || | |_/ | | \_| | || | | | | | +| | | | | || | | _| _ | || | | |\ \| | | || | | | | || | | | | | +| | \ `.___.'\ | || | _| |___/ | | || | _| |_\ |_ | || | _| |_ | || | _| |_ | | +| | `._____.' | || | |_________| | || ||_____|\____| | || | |_____| | || | |_____| | | +| | | || | | || | | || | | || | | | +| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' | + '----------------' '----------------' '----------------' '----------------' '----------------' + + +=== 'CENTI' Token contract with following features === + => ERC20 Compliance + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => Burnable and minting + => user whitelisting + => air drop (active) + => In-built buy/sell tokens + => Upgradeability using Unstructured Storage: https://github.com/zeppelinos/labs/tree/master/upgradeability_using_unstructured_storage + + +======================= Quick Stats =================== + => Name : CENTI + => Symbol : CEN + => Total supply: 10,000,000,000 (10 Billion) + => Decimals : 2 + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + => Community Audit by Bug Bounty program + + +------------------------------------------------------------------- + Copyright (c) 2020 onwards CENTI Token Inc. ( https://centitoken.com ) + Contract designed with ? by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + + + + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + address payable internal newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + emit OwnershipTransferred(address(0), owner); + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +//****************************************************************************// +//--------------------- MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract CENTI is owned { + + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string constant private _name = "CENTI"; + string constant private _symbol = "CEN"; + uint256 constant private _decimals = 2; + uint256 private _totalSupply = 10000000000 * (10**_decimals); //10 billion tokens + uint256 constant public maxSupply = 10000000000 * (10**_decimals); //10 billion tokens + bool public safeguard; //putting safeguard on will halt all non-owner functions + + // This creates a mapping with all data storage + mapping (address => uint256) private _balanceOf; + mapping (address => mapping (address => uint256)) private _allowance; + mapping (address => bool) public frozenAccount; + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenAccounts(address target, bool frozen); + + // This will log approval of token Transfer + event Approval(address indexed from, address indexed spender, uint256 value); + + + + /*====================================== + = STANDARD ERC20 FUNCTIONS = + ======================================*/ + + /** + * Returns name of token + */ + function name() public pure returns(string memory){ + return _name; + } + + /** + * Returns symbol of token + */ + function symbol() public pure returns(string memory){ + return _symbol; + } + + /** + * Returns decimals of token + */ + function decimals() public pure returns(uint256){ + return _decimals; + } + + /** + * Returns totalSupply of token. + */ + function totalSupply() public view returns (uint256) { + return _totalSupply; + } + + /** + * Returns balance of token + */ + function balanceOf(address user) public view returns(uint256){ + return _balanceOf[user]; + } + + /** + * Returns allowance of token + */ + function allowance(address owner, address spender) public view returns (uint256) { + return _allowance[owner][spender]; + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguard); + require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + // overflow and undeflow checked by SafeMath Library + _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender + _balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + //checking of allowance and token value is done by SafeMath + _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + /* AUDITOR NOTE: + Many dex and dapps pre-approve large amount of tokens to save gas for subsequent transaction. This is good use case. + On flip-side, some malicious dapp, may pre-approve large amount and then drain all token balance from user. + So following condition is kept in commented. It can be be kept that way or not based on client's consent. + */ + //require(_balanceOf[msg.sender] >= _value, "Balance does not have enough tokens"); + _allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + /** + * @dev Increase the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To increment + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * Emits an Approval event. + * @param spender The address which will spend the funds. + * @param value The amount of tokens to increase the allowance by. + */ + function increase_allowance(address spender, uint256 value) public returns (bool) { + require(spender != address(0)); + _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(value); + emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); + return true; + } + + /** + * @dev Decrease the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To decrement + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * Emits an Approval event. + * @param spender The address which will spend the funds. + * @param value The amount of tokens to decrease the allowance by. + */ + function decrease_allowance(address spender, uint256 value) public returns (bool) { + require(spender != address(0)); + _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(value); + emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); + return true; + } + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + constructor() public{ + //sending all the tokens to Owner + _balanceOf[owner] = _totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, _totalSupply); + } + + function () external payable { + buyTokens(); + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of enough token balance is done by SafeMath + _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); // Subtract from the sender + _totalSupply = _totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of allowance and token value is done by SafeMath + _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the targeted balance + _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + _totalSupply = _totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + emit Transfer(_from, address(0), _value); + return true; + } + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenAccounts(target, freeze); + } + + /** + * @notice Create `mintedAmount` tokens and send it to `target` + * @param target Address to receive the tokens + * @param mintedAmount the amount of tokens it will receive + */ + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + require(_totalSupply.add(mintedAmount) <= maxSupply, "Cannot Mint more than maximum supply"); + _balanceOf[target] = _balanceOf[target].add(mintedAmount); + _totalSupply = _totalSupply.add(mintedAmount); + emit Transfer(address(0), target, mintedAmount); + } + + + + /** + * Owner can transfer tokens from contract to owner address + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + + /*************************************/ + /* Section for User Air drop */ + /*************************************/ + + /** + * Run an ACTIVE Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public returns(bool) { + uint256 totalAddresses = recipients.length; + require(totalAddresses <= 150,"Too many recipients"); + for(uint i = 0; i < totalAddresses; i++) + { + //This will loop through all the recipients and send them the specified tokens + //Input data validation is unncessary, as that is done by SafeMath and which also saves some gas. + transfer(recipients[i], tokenAmount[i]); + } + return true; + } + + + + + /*************************************/ + /* Section for User whitelisting */ + /*************************************/ + bool public whitelistingStatus; + mapping (address => bool) public whitelisted; + + /** + * Change whitelisting status on or off + * + * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. + */ + function changeWhitelistingStatus() onlyOwner public{ + if (whitelistingStatus == false){ + whitelistingStatus = true; + } + else{ + whitelistingStatus = false; + } + } + + /** + * Whitelist any user address - only Owner can do this + * + * It will add user address in whitelisted mapping + */ + function whitelistUser(address userAddress, bool status) onlyOwner public{ + require(whitelistingStatus == true); + require(userAddress != address(0)); + whitelisted[userAddress] = status; + } + + /** + * Whitelist Many user address at once - only Owner can do this + * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack + * It will add user address in whitelisted mapping + */ + function whitelistManyUsers(address[] memory userAddresses, bool status) onlyOwner public{ + require(whitelistingStatus == true); + uint256 addressCount = userAddresses.length; + require(addressCount <= 150,"Too many addresses"); + for(uint256 i = 0; i < addressCount; i++){ + whitelisted[userAddresses[i]] = status; + } + } + + + /*************************************/ + /* Section for Buy/Sell of tokens */ + /*************************************/ + + uint256 public sellPrice = 100; // 2 prcision by default for 1:1 + uint256 public buyPrice = 100; // 2 precision for this variable. so by default, it will be 1:1 with ETH + + /** + * Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth + * newSellPrice Price the users can sell to the contract + * newBuyPrice Price users can buy from the contract + */ + function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { + sellPrice = newSellPrice; //sellPrice is 1 Token = ?? WEI + buyPrice = newBuyPrice; //buyPrice is 1 ETH = ?? Tokens + } + + /** + * Buy tokens from contract by sending ether + * buyPrice is 1 ETH = ?? Tokens + */ + + function buyTokens() payable public { + //checking whitelisting status + if(whitelistingStatus){ + require(whitelisted[msg.sender], 'User is not whitelisted'); + } + // calculates the amount. + // devided by 100, because buyPrice is in 2 precision + // devided by 1e16 as ether is in 1e18 and token is in 1e2 precision + uint amount = msg.value * buyPrice / 100 / 1e16; + _transfer(address(this), msg.sender, amount); // makes the transfers + // did not transfer ether to owner to save gas cost. and owner can always withdraw by calling manualWithdrawEther function + } + + /** + * Sell `amount` tokens to contract + * amount amount of tokens to be sold + */ + function sellTokens(uint256 amount) public { + //checking whitelisting status + if(whitelistingStatus){ + require(whitelisted[msg.sender], 'User is not whitelisted'); + } + //calculates ether amount + uint256 etherAmount = amount * 1e16 * sellPrice/100; + // transfers token and ether + _transfer(msg.sender, address(this), amount); // makes the transfers + msg.sender.transfer(etherAmount); // sends ether to the seller. It's important to do this last to avoid recursion attacks + } + + + + +} \ No newline at end of file diff --git a/ERC20 Tokens/Cointorox.sol b/ERC20 Tokens/Cointorox.sol new file mode 100644 index 0000000..0f95246 --- /dev/null +++ b/ERC20 Tokens/Cointorox.sol @@ -0,0 +1,364 @@ +pragma solidity 0.5.0; /* + + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + ██████╗ ██████╗ ██╗███╗ ██╗████████╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗ +██╔════╝██╔═══██╗██║████╗ ██║╚══██╔══╝██╔═══██╗██╔══██╗██╔═══██╗╚██╗██╔╝ +██║ ██║ ██║██║██╔██╗ ██║ ██║ ██║ ██║██████╔╝██║ ██║ ╚███╔╝ +██║ ██║ ██║██║██║╚██╗██║ ██║ ██║ ██║██╔══██╗██║ ██║ ██╔██╗ +╚██████╗╚██████╔╝██║██║ ╚████║ ██║ ╚██████╔╝██║ ██║╚██████╔╝██╔╝ ██╗ + ╚═════╝ ╚═════╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ + + +// ---------------------------------------------------------------------------- +// 'Cointorox' Token contract with following features +// => ERC20 Compliance +// => Higher degree of control by owner +// => selfdestruct ability by owner +// => SafeMath implementation +// => User whitelisting +// => Burnable and no minting +// +// Name : Cointorox +// Symbol : OROX +// Total supply: 10,000,000 (10 Million) +// Decimals : 18 +// +// Copyright (c) 2018 Cointorox Inc. ( https://cointorox.com ) +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- + +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// + /** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ + library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + } + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + + contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } + } + + +//***************************************************************// +//------------------ ERC20 Standard Template -------------------// +//***************************************************************// + + contract TokenERC20 { + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint256 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor ( + uint256 initialSupply, + string memory tokenName, + string memory tokenSymbol + ) public { + totalSupply = initialSupply.mul(10**decimals); // Update total supply with the decimal amount + balanceOf[msg.sender] = totalSupply; // All the tokens will be sent to owner + name = tokenName; // Set the name for display purposes + symbol = tokenSymbol; // Set the symbol for display purposes + emit Transfer(address(0), msg.sender, totalSupply);// Emit event to log this transaction + + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != address(0x0)); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + + } + +//****************************************************************************// +//--------------------- COINTOROX MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + + contract Cointorox is owned, TokenERC20 { + + /*************************************/ + /* User whitelisting functionality */ + /*************************************/ + bool public whitelistingStatus = false; + mapping (address => bool) public whitelisted; + + /** + * Change whitelisting status on or off + * + * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. + */ + function changeWhitelistingStatus() onlyOwner public{ + if (whitelistingStatus == false){ + whitelistingStatus = true; + } + else{ + whitelistingStatus = false; + } + } + + /** + * Whitelist any user address - only Owner can do this + * + * It will add user address in whitelisted mapping + */ + function whitelistUser(address userAddress) onlyOwner public{ + require(whitelistingStatus == true); + require(userAddress != address(0x0)); + whitelisted[userAddress] = true; + } + + /** + * Whitelist Many user address at once - only Owner can do this + * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack + * It will add user address in whitelisted mapping + */ + function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ + require(whitelistingStatus == true); + uint256 addressCount = userAddresses.length; + require(addressCount <= 150); + for(uint256 i = 0; i < addressCount; i++){ + require(userAddresses[i] != address(0x0)); + whitelisted[userAddresses[i]] = true; + } + } + + + + /*********************************/ + /* Code for the ERC20 OROX Token */ + /*********************************/ + + /* Public variables of the token */ + string private tokenName = "Cointorox"; + string private tokenSymbol = "OROX"; + uint256 private initialSupply = 10000000; //10 Million + + + /* Records for the fronzen accounts */ + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with initial supply tokens to the creator of the contract */ + constructor () TokenERC20(initialSupply, tokenName, tokenSymbol) public {} + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead + require (balanceOf[_from] >= _value); // Check if the sender has enough + require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + //selfdestruct function. just in case owner decided to destruct this contract. + function destructContract()onlyOwner public{ + selfdestruct(owner); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + +} diff --git a/ERC20 Tokens/EROX-token.sol b/ERC20 Tokens/EROX-token.sol new file mode 100644 index 0000000..42e5f74 --- /dev/null +++ b/ERC20 Tokens/EROX-token.sol @@ -0,0 +1,568 @@ +pragma solidity 0.5.9; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + ++ + + + + + + ++----+ +--+ +----+ +--+ +---+ ++++ ++ ++ + +++ ++--+ +--+ +--+ ++ ++ + ++ +++ ++ + ++------+ +-+ +-+ +------+ +-----+ +-----+ +-+ +-+ + + +=== 'Eredox' Token contract with following features === + => ERC20 Compliance + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => Burnable and minting + => user whitelisting + => Token swap functionality (implemented for the future use) + => Stagged ICO + + +======================= Quick Stats =================== + => Name : Eredox + => Symbol : EROX + => Total supply: 4,000,000,000 (4 Billion) + => Reserved for ICO: 50% + => Decimals : 18 + + +------------------------------------------------------------------- + Copyright (c) 2019 onwards Eredox Pty Ltd. ( https://Eredox.com ) + Contract designed by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + address payable internal newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +//****************************************************************************// +//--------------------- MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract Eredox is owned { + + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string constant public name = "Eredox"; + string constant public symbol = "EROX"; + uint256 constant public decimals = 18; + uint256 public totalSupply = 4000000000 * (10**decimals); //4 billion tokens + uint256 public maxTokenSupply; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + bool public tokenSwap = false; //when tokenSwap will be on then all the token transfer to contract will trigger token swap + + // This creates a mapping with all data storage + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + mapping (address => bool) public frozenAccount; + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenAccount(address target, bool frozen); + + // This will log approval of token Transfer + event Approval(address indexed from, address indexed spender, uint256 value); + + // This is for token swap + event TokenSwap(address indexed user, uint256 value); + + + /*====================================== + = STANDARD ERC20 FUNCTIONS = + ======================================*/ + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + + //code for token swap. + if(tokenSwap && _to == address(this)){ + //fire tokenSwap event. This event can be listed by oracle and issue tokens of ethereum or another blockchain + emit TokenSwap(msg.sender, _value); + } + + //checking conditions + require(!safeguard); + require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + // overflow and undeflow checked by SafeMath Library + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value, "Balance does not have enough tokens"); + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + constructor() public{ + //sending 50% to owner and keep remaining 50% in smart contract for ICO + uint256 tokens = totalSupply / 2; + balanceOf[owner] = tokens; + balanceOf[address(this)] = tokens; + + maxTokenSupply = totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, tokens); + emit Transfer(address(0), address(this), tokens); + } + + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of enough token balance is done by SafeMath + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of allowance and token value is done by SafeMath + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + emit Transfer(_from, address(0), _value); + return true; + } + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenAccount(target, freeze); + } + + /** + * @notice Create `mintedAmount` tokens and send it to `target` + * @param target Address to receive the tokens + * @param mintedAmount the amount of tokens it will receive + */ + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + + require(totalSupply <= maxTokenSupply, 'Minting not possible more than maxTokenSupply'); + + balanceOf[target] = balanceOf[target].add(mintedAmount); + totalSupply = totalSupply.add(mintedAmount); + emit Transfer(address(0), target, mintedAmount); + } + + + + /** + * Owner can transfer tokens from contract to owner address + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + /** + * This function allows enable admins to start or stop token swaps. + */ + function changeTokenSwapStatus() public onlyOwner{ + if (tokenSwap == false){ + tokenSwap = true; + } + else{ + tokenSwap = false; + } + } + + + + + /*************************************/ + /* Section for User whitelisting */ + /*************************************/ + bool public whitelistingStatus; + mapping (address => bool) public whitelisted; + + /** + * Change whitelisting status on or off + * + * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. + */ + function changeWhitelistingStatus() onlyOwner public{ + if (whitelistingStatus == false){ + whitelistingStatus = true; + } + else{ + whitelistingStatus = false; + } + } + + /** + * Whitelist any user address - only Owner can do this + * + * It will add user address in whitelisted mapping + */ + function whitelistUser(address userAddress) onlyOwner public{ + require(whitelistingStatus == true); + require(userAddress != address(0)); + whitelisted[userAddress] = true; + } + + /** + * Whitelist Many user address at once - only Owner can do this + * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack + * It will add user address in whitelisted mapping + */ + function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ + require(whitelistingStatus == true); + uint256 addressCount = userAddresses.length; + require(addressCount <= 150); + for(uint256 i = 0; i < addressCount; i++){ + whitelisted[userAddresses[i]] = true; + } + } + + + + + /******************************/ + /* Code for the Crowdsale */ + /******************************/ + + /* TECHNICAL SPECIFICATIONS: + + => Private-sale Starts : TBA + => ICO will start : TBA + => ICO Ends : TBA + => Coins reserved for ICO : 2 Billion (50% of total supply) + => Minimum Contribution : 0.01 ETH (Private-sale and Main-sale) + => Hard cap : 157,500 ETH + => Token Prices: + * Private sale : 1 ETH = 18,667 EROX + * Main Sale Stage 1 : 1 ETH = 11,200 EROX + * Main Sale Stage 2 : 1 ETH = 10,000 EROX + * Main Sale Stage 3 : 1 ETH = 9,600 EROX + * Main Sale Stage 4 : 1 ETH = 9,200 EROX + * Main Sale Stage 5 : 1 ETH = 8,640 EROX + * Main Sale Stage 6 : 1 ETH = 8,000 EROX + + */ + + //public variables for the Crowdsale + uint256 public datePivateSale = 1541059200; + uint256 public dateICOStage1 = 1546329600; + uint256 public dateICOStage2 = 1546329600; + uint256 public dateICOStage3 = 1546329600; + uint256 public dateICOStage4 = 1546329600; + uint256 public dateICOStage5 = 1546329600; + uint256 public dateICOStage6 = 1546329600; + uint256 public dateICOFinished = 1546329600; + + uint256 public tokenPricePrivateSale = 18667; + uint256 public tokenPriceMainSale1 = 11200; + uint256 public tokenPriceMainSale2 = 10000; + uint256 public tokenPriceMainSale3 = 9600; + uint256 public tokenPriceMainSale4 = 9200; + uint256 public tokenPriceMainSale5 = 8640; + uint256 public tokenPriceMainSale6 = 8000; + + uint256 public tokensSold; // how many tokens sold through crowdsale + uint256 public etherRaised; // how much ether raised through crowdsale + uint256 public minimumContribution = 1e16; // Minimum amount to invest - 0.01 ETH (in 18 decimal format) + uint256 public hardCap = 157500 * (10 ** decimals); + + /** + * fallback function, only accepts ether if pre-sale or ICO is running or Reject + */ + function () payable external { + + require(!safeguard); + require(!frozenAccount[msg.sender]); + if(whitelistingStatus == true) require(whitelisted[msg.sender]); + require(datePivateSale < now); + require(dateICOFinished > now); + require(msg.value >= minimumContribution); //converting msg.value wei into 2 decimal format + require (etherRaised <= hardCap); + + // calculate token amount to be sent + uint256 token = msg.value.mul(findCurrentTokenPrice()); //weiamount * current token price + + //adding purchase bonus if applicable + token = token.add(token * purchaseBonusPercentage(msg.value) / 100 ); + + tokensSold = tokensSold.add(token); + etherRaised += msg.value; + _transfer(address(this), msg.sender, token); //makes the transfers + + //send Ether to owner + forwardEherToOwner(); + } + + /** + * Calculates price of token based on ICO Stage + */ + function findCurrentTokenPrice() public view returns (uint256){ + + uint256 currentTimeStamp = now; + + if(datePivateSale <= currentTimeStamp && dateICOStage1 > currentTimeStamp ) return tokenPricePrivateSale; + + if(dateICOStage1 <= currentTimeStamp && dateICOStage2 > currentTimeStamp ) return tokenPriceMainSale1; + + if(dateICOStage2 <= currentTimeStamp && dateICOStage3 > currentTimeStamp ) return tokenPriceMainSale2; + + if(dateICOStage3 <= currentTimeStamp && dateICOStage4 > currentTimeStamp ) return tokenPriceMainSale3; + + if(dateICOStage4 <= currentTimeStamp && dateICOStage5 > currentTimeStamp ) return tokenPriceMainSale4; + + if(dateICOStage5 <= currentTimeStamp && dateICOStage6 > currentTimeStamp ) return tokenPriceMainSale5; + + if(dateICOStage6 <= currentTimeStamp && dateICOFinished > currentTimeStamp ) return tokenPriceMainSale6; + + //by default it will return zero + + } + + /** + * This will calculate the percentage for the purchase bonus. + * Purchase bonus is certain percentage of extra tokens depending on amount of ether invested. + */ + function purchaseBonusPercentage(uint256 etherInvested) pure internal returns(uint256){ + + if(etherInvested < (5 * 1e18)) return 0; + + if(etherInvested >= (5 * 1e18) && etherInvested < (15 * 1e18)) return 5; + + if(etherInvested >= (15 * 1e18)) return 15; + + } + + + /** + * Automatocally forwards ether from smart contract to owner address + */ + function forwardEherToOwner() internal { + owner.transfer(msg.value); + } + + + /** + * updates ICO dates + */ + function updateICOdates(uint256 _datePivateSale, uint256 _dateICOStage1, uint256 _dateICOStage2, uint256 _dateICOStage3, uint256 _dateICOStage4, uint256 _dateICOStage5, uint256 _dateICOStage6, uint256 _dateICOFinished ) public onlyOwner returns(string memory){ + + datePivateSale = _datePivateSale; + dateICOStage1 = _dateICOStage1; + dateICOStage2 = _dateICOStage2; + dateICOStage3 = _dateICOStage3; + dateICOStage4 = _dateICOStage4; + dateICOStage5 = _dateICOStage5; + dateICOStage6 = _dateICOStage6; + dateICOFinished = _dateICOFinished; + + return("ICO Dates are updated successfully"); + } + + /** + * update token price for all ico stages + */ + function updateTokenPrices(uint256 _tokenPricePrivateSale, uint256 _tokenPriceMainSale1, uint256 _tokenPriceMainSale2, uint256 _tokenPriceMainSale3, uint256 _tokenPriceMainSale4, uint256 _tokenPriceMainSale5, uint256 _tokenPriceMainSale6 ) public onlyOwner returns(string memory){ + + tokenPricePrivateSale = _tokenPricePrivateSale; + tokenPriceMainSale1 = _tokenPriceMainSale1; + tokenPriceMainSale2 = _tokenPriceMainSale2; + tokenPriceMainSale3 = _tokenPriceMainSale3; + tokenPriceMainSale4 = _tokenPriceMainSale4; + tokenPriceMainSale5 = _tokenPriceMainSale5; + tokenPriceMainSale6 = _tokenPriceMainSale6; + + return("Token prices are updated successfully"); + } + + +} diff --git a/ERC20 Tokens/EnvoyChain.sol b/ERC20 Tokens/EnvoyChain.sol new file mode 100644 index 0000000..e4aac8f --- /dev/null +++ b/ERC20 Tokens/EnvoyChain.sol @@ -0,0 +1,726 @@ +pragma solidity 0.5.5; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + +███████╗███╗ ██╗██╗ ██╗ ██████╗ ██╗ ██╗ ██████╗██╗ ██╗ █████╗ ██╗███╗ ██╗ +██╔════╝████╗ ██║██║ ██║██╔═══██╗╚██╗ ██╔╝ ██╔════╝██║ ██║██╔══██╗██║████╗ ██║ +█████╗ ██╔██╗ ██║██║ ██║██║ ██║ ╚████╔╝ ██║ ███████║███████║██║██╔██╗ ██║ +██╔══╝ ██║╚██╗██║╚██╗ ██╔╝██║ ██║ ╚██╔╝ ██║ ██╔══██║██╔══██║██║██║╚██╗██║ +███████╗██║ ╚████║ ╚████╔╝ ╚██████╔╝ ██║ ╚██████╗██║ ██║██║ ██║██║██║ ╚████║ +╚══════╝╚═╝ ╚═══╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ + + + +// ---------------------------------------------------------------------------- +// 'Envoy' Token contract with following features +// => ERC20 Compliance +// => Higher degree of control by owner - safeguard functionality +// => SafeMath implementation +// => Burnable and minting +// => user whitelisting +// => air drop (active and passive) +// => in-built buy/sell functions +// => in-built ICO simple phased +// => upgradibilitiy +// +// Name : Envoy +// Symbol : NVOY +// Total supply: 250,000,000 +// Decimals : 18 +// +// Copyright 2019 onwards - Envoy Group ( http://envoychain.io ) +// Special thanks to openzeppelin for inspiration: +// https://github.com/zeppelinos/labs/tree/master/upgradeability_using_unstructured_storage +// ---------------------------------------------------------------------------- +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } +} + + + +//****************************************************************************// +//--------------------- MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract EnvoyChain_v1 is owned { + + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint256 public decimals; + uint256 public totalSupply; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + + // This creates a mapping with all data storage + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + mapping (address => bool) public frozenAccount; + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenFunds(address target, bool frozen); + + + + /*====================================== + = STANDARD ERC20 FUNCTIONS = + ======================================*/ + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguard); + require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + // overflow and undeflow checked by SafeMath Library + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + constructor() public{ + //sending all the tokens to Owner + balanceOf[owner] = totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, totalSupply); + } + + function () external payable { + + buyTokens(); + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of enough token balance is done by SafeMath + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of allowance and token value is done by SafeMath + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + /** + * @notice Create `mintedAmount` tokens and send it to `target` + * @param target Address to receive the tokens + * @param mintedAmount the amount of tokens it will receive + */ + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + balanceOf[target] = balanceOf[target].add(mintedAmount); + totalSupply = totalSupply.add(mintedAmount); + emit Transfer(address(0), target, mintedAmount); + } + + + + /** + * Owner can transfer tokens from contract to owner address + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + /*************************************/ + /* Section for User Air drop */ + /*************************************/ + + bool public passiveAirdropStatus; + uint256 public passiveAirdropTokensAllocation; + uint256 public airdropAmount; //in wei + uint256 public passiveAirdropTokensSold; + mapping(uint256 => mapping(address => bool)) public airdropClaimed; + uint256 internal airdropClaimedIndex; + uint256 public airdropFee = 0.05 ether; + + /** + * This function to start a passive air drop by admin only + * Admin have to put airdrop amount (in wei) and total toens allocated for it. + * Admin must keep allocated tokens in the contract + */ + function startNewPassiveAirDrop(uint256 passiveAirdropTokensAllocation_, uint256 airdropAmount_ ) public onlyOwner { + passiveAirdropTokensAllocation = passiveAirdropTokensAllocation_; + airdropAmount = airdropAmount_; + passiveAirdropStatus = true; + } + + /** + * This function will stop any ongoing passive airdrop + */ + function stopPassiveAirDropCompletely() public onlyOwner{ + passiveAirdropTokensAllocation = 0; + airdropAmount = 0; + airdropClaimedIndex++; + passiveAirdropStatus = false; + } + + /** + * This function called by user who want to claim passive air drop. + * He can only claim air drop once, for current air drop. If admin stop an air drop and start fresh, then users can claim again (once only). + */ + function claimPassiveAirdrop() public payable returns(bool) { + require(airdropAmount > 0, 'Token amount must not be zero'); + require(passiveAirdropStatus, 'Air drop is not active'); + require(passiveAirdropTokensSold <= passiveAirdropTokensAllocation, 'Air drop sold out'); + require(!airdropClaimed[airdropClaimedIndex][msg.sender], 'user claimed air drop already'); + require(!isContract(msg.sender), 'No contract address allowed to claim air drop'); + require(msg.value >= airdropFee, 'Not enough ether to claim this airdrop'); + + _transfer(address(this), msg.sender, airdropAmount); + passiveAirdropTokensSold += airdropAmount; + airdropClaimed[airdropClaimedIndex][msg.sender] = true; + return true; + } + + function changePassiveAirdropAmount(uint256 newAmount) public onlyOwner{ + airdropAmount = newAmount; + } + + function isContract(address _address) public view returns (bool){ + uint32 size; + assembly { + size := extcodesize(_address) + } + return (size > 0); + } + + function updateAirdropFee(uint256 newFee) public onlyOwner{ + airdropFee = newFee; + } + + /** + * Run an ACTIVE Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdropACTIVE(address[] memory recipients,uint256 tokenAmount) public onlyOwner { + require(recipients.length <= 150); + uint256 totalAddresses = recipients.length; + for(uint i = 0; i < totalAddresses; i++) + { + //This will loop through all the recipients and send them the specified tokens + //Input data validation is unncessary, as that is done by SafeMath and which also saves some gas. + _transfer(address(this), recipients[i], tokenAmount); + } + } + + + + + /*************************************/ + /* Section for User whitelisting */ + /*************************************/ + bool public whitelistingStatus; + mapping (address => bool) public whitelisted; + + /** + * Change whitelisting status on or off + * + * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. + */ + function changeWhitelistingStatus() onlyOwner public{ + if (whitelistingStatus == false){ + whitelistingStatus = true; + } + else{ + whitelistingStatus = false; + } + } + + /** + * Whitelist any user address - only Owner can do this + * + * It will add user address in whitelisted mapping + */ + function whitelistUser(address userAddress) onlyOwner public{ + require(whitelistingStatus == true); + require(userAddress != address(0)); + whitelisted[userAddress] = true; + } + + /** + * Whitelist Many user address at once - only Owner can do this + * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack + * It will add user address in whitelisted mapping + */ + function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ + require(whitelistingStatus == true); + uint256 addressCount = userAddresses.length; + require(addressCount <= 150); + for(uint256 i = 0; i < addressCount; i++){ + require(userAddresses[i] != address(0)); + whitelisted[userAddresses[i]] = true; + } + } + + + /*************************************/ + /* Section for Buy/Sell of tokens */ + /*************************************/ + + uint256 public sellPrice; + uint256 public buyPrice; + + /** + * Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth + * newSellPrice Price the users can sell to the contract + * newBuyPrice Price users can buy from the contract + */ + function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { + sellPrice = newSellPrice; //sellPrice is 1 Token = ?? WEI + buyPrice = newBuyPrice; //buyPrice is 1 ETH = ?? Tokens + } + + /** + * Buy tokens from contract by sending ether + * buyPrice is 1 ETH = ?? Tokens + */ + + function buyTokens() payable public { + uint amount = msg.value * buyPrice; // calculates the amount + _transfer(address(this), msg.sender, amount); // makes the transfers + } + + /** + * Sell `amount` tokens to contract + * amount amount of tokens to be sold + */ + function sellTokens(uint256 amount) public { + uint256 etherAmount = amount * sellPrice/(10**decimals); + require(address(this).balance >= etherAmount); // checks if the contract has enough ether to buy + _transfer(msg.sender, address(this), amount); // makes the transfers + msg.sender.transfer(etherAmount); // sends ether to the seller. It's important to do this last to avoid recursion attacks + } + + + /********************************************/ + /* Custom Code for the contract Upgradation */ + /********************************************/ + + bool internal initialized; + function initialize( + address payable _owner + ) public { + require(!initialized); + require(owner == address(0)); //When this methods called, then owner address must be zero + + name = "Envoy"; + symbol = "NVOY"; + decimals = 18; + totalSupply = 250000000 * (10**decimals); + owner = _owner; + + //sending all the tokens to Owner + balanceOf[owner] = totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, totalSupply); + + initialized = true; + } + + +} + + + + + + + +//********************************************************************************// +//------------- MAIN PROXY CONTRACTS (UPGRADEABILITY) SECTION STARTS ------------// +//********************************************************************************// + + +/****************************************/ +/* Proxy Contract */ +/****************************************/ +/** + * @title Proxy + * @dev Gives the possibility to delegate any call to a foreign implementation. + */ +contract Proxy { + /** + * @dev Tells the address of the implementation where every call will be delegated. + * @return address of the implementation to which it will be delegated + */ + function implementation() public view returns (address); + + /** + * @dev Fallback function allowing to perform a delegatecall to the given implementation. + * This function will return whatever the implementation call returns + */ + function () payable external { + address _impl = implementation(); + require(_impl != address(0)); + + 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) } + } + } +} + + +/****************************************/ +/* UpgradeabilityProxy Contract */ +/****************************************/ +/** + * @title UpgradeabilityProxy + * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded + */ +contract UpgradeabilityProxy is Proxy { + /** + * @dev This event will be emitted every time the implementation gets upgraded + * @param implementation representing the address of the upgraded implementation + */ + event Upgraded(address indexed implementation); + + // Storage position of the address of the current implementation + bytes32 private constant implementationPosition = keccak256("EtherAuthority.io.proxy.implementation"); + + /** + * @dev Constructor function + */ + constructor () public {} + + /** + * @dev Tells the address of the current implementation + * @return address of the current implementation + */ + function implementation() public view returns (address impl) { + bytes32 position = implementationPosition; + assembly { + impl := sload(position) + } + } + + /** + * @dev Sets the address of the current implementation + * @param newImplementation address representing the new implementation to be set + */ + function setImplementation(address newImplementation) internal { + bytes32 position = implementationPosition; + assembly { + sstore(position, newImplementation) + } + } + + /** + * @dev Upgrades the implementation address + * @param newImplementation representing the address of the new implementation to be set + */ + function _upgradeTo(address newImplementation) internal { + address currentImplementation = implementation(); + require(currentImplementation != newImplementation); + setImplementation(newImplementation); + emit Upgraded(newImplementation); + } +} + +/****************************************/ +/* OwnedUpgradeabilityProxy contract */ +/****************************************/ +/** + * @title OwnedUpgradeabilityProxy + * @dev This contract combines an upgradeability proxy with basic authorization control functionalities + */ +contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { + /** + * @dev Event to show ownership has been transferred + * @param previousOwner representing the address of the previous owner + * @param newOwner representing the address of the new owner + */ + event ProxyOwnershipTransferred(address previousOwner, address newOwner); + + // Storage position of the owner of the contract + bytes32 private constant proxyOwnerPosition = keccak256("EtherAuthority.io.proxy.owner"); + + /** + * @dev the constructor sets the original owner of the contract to the sender account. + */ + constructor () public { + setUpgradeabilityOwner(msg.sender); + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyProxyOwner() { + require(msg.sender == proxyOwner()); + _; + } + + /** + * @dev Tells the address of the owner + * @return the address of the owner + */ + function proxyOwner() public view returns (address owner) { + bytes32 position = proxyOwnerPosition; + assembly { + owner := sload(position) + } + } + + /** + * @dev Sets the address of the owner + */ + function setUpgradeabilityOwner(address newProxyOwner) internal { + bytes32 position = proxyOwnerPosition; + assembly { + sstore(position, newProxyOwner) + } + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferProxyOwnership(address newOwner) public onlyProxyOwner { + require(newOwner != address(0)); + emit ProxyOwnershipTransferred(proxyOwner(), newOwner); + setUpgradeabilityOwner(newOwner); + } + + /** + * @dev Allows the proxy owner to upgrade the current version of the proxy. + * @param implementation representing the address of the new implementation to be set. + */ + function upgradeTo(address implementation) public onlyProxyOwner { + _upgradeTo(implementation); + } + + /** + * @dev Allows the proxy owner to upgrade the current version of the proxy and call the new implementation + * to initialize whatever is needed through a low level call. + * @param implementation representing the address of the new implementation to be set. + * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function + * signature of the implementation to be called with the needed payload + */ + function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner { + _upgradeTo(implementation); + (bool success,) = address(this).call.value(msg.value).gas(200000)(data); + require(success,'initialize function errored'); + } + + function generateData() public view returns(bytes memory){ + + return abi.encodeWithSignature("initialize(address)",msg.sender); + + } +} + + +/****************************************/ +/* EnvoyChain Proxy Contract */ +/****************************************/ + +/** + * @title EnvoyChain_proxy + * @dev This contract proxies FiatToken calls and enables FiatToken upgrades +*/ +contract EnvoyChain_proxy is OwnedUpgradeabilityProxy { + constructor() public OwnedUpgradeabilityProxy() { + } +} diff --git a/ERC20 Tokens/Ezoow.sol b/ERC20 Tokens/Ezoow.sol new file mode 100644 index 0000000..edf0f5a --- /dev/null +++ b/ERC20 Tokens/Ezoow.sol @@ -0,0 +1,337 @@ +pragma solidity 0.4.24; +// ---------------------------------------------------------------------------- +// 'Ezoow' contract +// +// Deployed to : 0x7acA75682eDd35355917B8bdDD85fc0821b3cc8f +// Symbol : EZW +// Name : Ezoow +// Total supply: 15,000,000,000 +// Decimals : 18 +// +// Copyright (c) 2018 Ezoow Inc. (https://ezoow.com) The MIT Licence. +// Contract designed by: GDO Infotech Pvt Ltd (https://GDO.co.in) +// ---------------------------------------------------------------------------- + + /** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ + library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + } + + contract owned { + address public owner; + using SafeMath for uint256; + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + owner = newOwner; + } + } + + interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external ; } + + contract TokenERC20 { + // Public variables of the token + using SafeMath for uint256; + string public name = "EZOOW"; + string public symbol = "EZW"; + uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply = 15000000000 * (1 ether); + uint256 public tokensForCrowdsale = 10000000000 * (1 ether); + uint256 public tokensForTeam = 4000000000 * (1 ether); + uint256 public tokensForOwner = 1000000000 * (1 ether); + + address public teamWallet = 0x7acA75682eDd35355917B8bdDD85fc0821b3cc8f; + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor() public { + + balanceOf[this] = tokensForCrowdsale; // 10 Billion will remain in contract for crowdsale + balanceOf[teamWallet] = tokensForTeam; // 4 Billion will be allocated to Team + balanceOf[msg.sender] = tokensForOwner; // 1 Billon will be sent to contract owner + + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != 0x0); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public { + _transfer(msg.sender, _to, _value); + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + allowance[msg.sender][_spender] = _value; + return true; + } + + /** + * Set allowance for other address and notify + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + * @param _extraData some extra information to send to the approved contract + */ + function approveAndCall(address _spender, uint256 _value, bytes _extraData) + public + returns (bool success) { + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + } + + /******************************************/ + /* ADVANCED TOKEN STARTS HERE */ + /******************************************/ + + contract Ezoow is owned, TokenERC20 { + + using SafeMath for uint256; + uint256 public startTime = 0; //client wants ICO run Infinite time, so startTimeStamp 0 + uint256 public endTime = 9999999999999999999999; //and entTimeStamp higher number + uint256 public exchangeRate = 20000000; // this is how many tokens for 1 Ether + uint256 public tokensSold = 0; // how many tokens sold in crowdsale + + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with initial supply tokens to the creator of the contract */ + constructor() TokenERC20() public {} + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead + require (balanceOf[_from] >= _value); // Check if the sender has enough + require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + //@dev fallback function, only accepts ether if ICO is running or Reject + function () payable public { + require(endTime > now); + require(startTime < now); + uint ethervalueWEI=msg.value; + // calculate token amount to be sent + uint256 token = ethervalueWEI.mul(exchangeRate); //weiamount * price + tokensSold = tokensSold.add(token); + _transfer(this, msg.sender, token); // makes the transfers + forwardEherToOwner(); + } + + //Automatocally forwards ether from smart contract to owner address + function forwardEherToOwner() internal { + owner.transfer(msg.value); + } + + //function to start an ICO. + //It requires: start and end timestamp, exchange rate in Wei, and token amounts to allocate for the ICO + //It will transfer allocated amount to the smart contract + function startIco(uint256 start,uint256 end, uint256 exchangeRateInWei, uint256 TokensAllocationForICO) onlyOwner public { + require(start < end); + uint256 tokenAmount = TokensAllocationForICO.mul(1 ether); + require(balanceOf[msg.sender] > tokenAmount); + startTime=start; + endTime=end; + exchangeRate = exchangeRateInWei; + approve(this,tokenAmount); + transfer(this,tokenAmount); + } + + //Stops an ICO. + //It will also transfer remaining tokens to owner + function stopICO() onlyOwner public{ + endTime = 0; + uint256 tokenAmount=balanceOf[this]; + _transfer(this, msg.sender, tokenAmount); + } + + //function to check wheter ICO is running or not. + function isICORunning() public view returns(bool){ + if(endTime > now && startTime < now){ + return true; + }else{ + return false; + } + } + + //Function to set ICO Exchange rate. + function setICOExchangeRate(uint256 newExchangeRate) onlyOwner public { + exchangeRate=newExchangeRate; + } + + //Just in case, owner wants to transfer Tokens from contract to owner address + function manualWithdrawToken(uint256 _amount) onlyOwner public { + uint256 tokenAmount = _amount.mul(1 ether); + _transfer(this, msg.sender, tokenAmount); + } + + //Just in case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + uint256 amount=address(this).balance; + owner.transfer(amount); + } + + /// @notice Create `mintedAmount` tokens and send it to `target` + /// @param target Address to receive the tokens + /// @param mintedAmount the amount of tokens it will receive + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + balanceOf[target] = balanceOf[target].add(mintedAmount); + totalSupply = totalSupply.add(mintedAmount); + emit Transfer(0, this, mintedAmount); + emit Transfer(this, target, mintedAmount); + } + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + + + } diff --git a/ERC20 Tokens/FSM.sol b/ERC20 Tokens/FSM.sol new file mode 100644 index 0000000..5f3717c --- /dev/null +++ b/ERC20 Tokens/FSM.sol @@ -0,0 +1,356 @@ +pragma solidity 0.5.8; /* + + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + .----------------. .----------------. .----------------. +| .--------------. || .--------------. || .--------------. | +| | _________ | || | _______ | || | ____ ____ | | +| | |_ ___ | | || | / ___ | | || ||_ \ / _|| | +| | | |_ \_| | || | | (__ \_| | || | | \/ | | | +| | | _| | || | '.___`-. | || | | |\ /| | | | +| | _| |_ | || | |`\____) | | || | _| |_\/_| |_ | | +| | |_____| | || | |_______.' | || ||_____||_____|| | +| | | || | | || | | | +| '--------------' || '--------------' || '--------------' | + '----------------' '----------------' '----------------' + + +=== 'FSM' Token contract with following features === + => ERC20 Compliance + => SafeMath implementation + => Burnable + => Deflationary + + +======================= Quick Stats =================== + => Name : FSM + => Symbol : FSM + => Total supply: 1,000,000,000 (1 Billion) + => Decimals : 18 + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + + +------------------------------------------------------------------- + Copyright (c) 2020 onwards FSM Inc. ( https://FSMtoken.io ) + Contract designed with ? by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + + +interface IERC20 { + function totalSupply() external view returns (uint256); + function balanceOf(address who) external view returns (uint256); + function allowance(address owner, address spender) external view returns (uint256); + function transfer(address to, uint256 value) external returns (bool); + function approve(address spender, uint256 value) external returns (bool); + function transferFrom(address from, address to, uint256 value) external returns (bool); + + event Transfer(address indexed from, address indexed to, uint256 value); + event Approval(address indexed owner, address indexed spender, uint256 value); +} + +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a / b; + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + + function ceil(uint256 a, uint256 m) internal pure returns (uint256) { + uint256 c = add(a,m); + uint256 d = sub(c,1); + return mul(div(d,m),m); + } +} + +contract ERC20Detailed is IERC20 { + + string private _name; + string private _symbol; + uint256 private _decimals; + + constructor(string memory name, string memory symbol, uint256 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(uint256) { + return _decimals; + } +} + + +contract owned { + address payable public owner; + address payable internal newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + emit OwnershipTransferred(address(0), owner); + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + +contract SFM is owned, ERC20Detailed { + + using SafeMath for uint256; + mapping (address => uint256) private _balances; + mapping (address => mapping (address => uint256)) private _allowed; + + string constant private tokenName = "SFM"; + string constant private tokenSymbol = "SFM"; + uint256 constant private tokenDecimals = 18; + uint256 private _totalSupply = 1000000000 * (10**tokenDecimals); // 1 Billion total supply + uint256 public basePercent = 100; + + //ICO Variables + uint256 public exchangeRate = 1 * (1e6); // exchange rate 1 TRX = 1 token + uint256 public icoTRXReceived; // how many TRX Received through ICO + uint256 public totalTokenSold; // how many tokens sold + uint256 public minimumContribution = 1000000; // Minimum amount to invest - 1 TRX (in SUN format) + + + constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { + _issue(msg.sender, _totalSupply); + } + + + //Fallback function. It accepts incoming ETH and issue tokens + function () payable external { + buyToken(); + } + + 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 cut(uint256 value) public view returns (uint256) { + uint256 roundValue = value.ceil(basePercent); + uint256 cutValue = roundValue.mul(basePercent).div(10000); + return cutValue; + } + + function transfer(address to, uint256 value) public returns (bool) { + require(to != address(0)); + + uint256 tokensToBurn = cut(value); + uint256 tokensToTransfer = value.sub(tokensToBurn); + + _balances[msg.sender] = _balances[msg.sender].sub(value); + _balances[to] = _balances[to].add(tokensToTransfer); + + _totalSupply = _totalSupply.sub(tokensToBurn); + + emit Transfer(msg.sender, to, tokensToTransfer); + emit Transfer(msg.sender, address(0), tokensToBurn); + return true; + } + + function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { + uint256 length = receivers.length; + require(length <= 150, 'Addresses can not be more than 150'); + for (uint256 i = 0; i < length; i++) { + transfer(receivers[i], amounts[i]); + } + } + + function approve(address spender, uint256 value) public returns (bool) { + require(spender != address(0)); + _allowed[msg.sender][spender] = value; + emit Approval(msg.sender, spender, value); + return true; + } + + function transferFrom(address from, address to, uint256 value) public returns (bool) { + require(value <= _balances[from]); + require(value <= _allowed[from][msg.sender]); + require(to != address(0)); + + _balances[from] = _balances[from].sub(value); + + uint256 tokensToBurn = cut(value); + uint256 tokensToTransfer = value.sub(tokensToBurn); + + _balances[to] = _balances[to].add(tokensToTransfer); + _totalSupply = _totalSupply.sub(tokensToBurn); + + _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); + + emit Transfer(from, to, tokensToTransfer); + emit Transfer(from, address(0), tokensToBurn); + + return true; + } + + function upAllowance(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 downAllowance(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 _issue(address account, uint256 amount) internal { + require(amount != 0); + _balances[account] = _balances[account].add(amount); + emit Transfer(address(0), account, amount); + } + + function destroy(uint256 amount) external { + _destroy(msg.sender, amount); + } + + function _destroy(address account, uint256 amount) internal { + require(amount != 0); + require(amount <= _balances[account]); + _totalSupply = _totalSupply.sub(amount); + _balances[account] = _balances[account].sub(amount); + emit Transfer(account, address(0), amount); + } + + function destroyFrom(address account, uint256 amount) external { + require(amount <= _allowed[account][msg.sender]); + _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); + _destroy(account, amount); + } + + /*=============================== + = ICO FUNCTIONS = + ===============================*/ + + function buyToken() payable public returns(uint) + { + + //checking conditions + require(msg.value >= minimumContribution, "less then minimum contribution"); + + //calculating tokens to issue + uint256 tokenTotal = msg.value * exchangeRate * (10**6); //here, tron is in 1e6, exchangeRate is in 1e6, and tokens are in 1e18 + + //updating state variables + icoTRXReceived += msg.value; + totalTokenSold += tokenTotal; + + //sending tokens. This crowdsale contract must hold enough tokens. + _balances[address(this)] = _balances[address(this)].sub(tokenTotal); + _balances[msg.sender] = _balances[msg.sender].add(tokenTotal); + emit Transfer(address(this), msg.sender, tokenTotal); + + //send fund to owner + owner.transfer(msg.value); + + return tokenTotal; + + } + + function setExchangeRate(uint256 _exchangeRateSUN) onlyOwner public returns (bool) + { + exchangeRate = _exchangeRateSUN; + return true; + } + + function setMinimumContribution(uint256 _minimumContributionSUN) onlyOwner public returns (bool) + { + minimumContribution = _minimumContributionSUN; + return true; + } + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner returns(string memory){ + // no need for overflow checking as that will be done by SafeMath + //sending tokens. This crowdsale contract must hold enough tokens. + _balances[address(this)] = _balances[address(this)].sub(tokenAmount); + _balances[msg.sender] = _balances[msg.sender].add(tokenAmount); + emit Transfer(address(this), msg.sender, tokenAmount); + return "Tokens withdrawn to owner wallet"; + } + + function manualWithdrawTRX() public onlyOwner returns(string memory){ + address(owner).transfer(address(this).balance); + return "Ether withdrawn to owner wallet"; + } + +} + +//****************************************************************************// +//--------------------- EASTER EGGS ---------------------// +//****************************************************************************// +/* + +1.The central creation myth is that an invisible and undetectable Flying Spaghetti Monster created the universe "after drinking heavily". +2.The Pastafarian conception of Heaven includes a beer volcano and a stripper (or sometimes prostitute) factory.The Pastafarian Hell is similar, except that the beer is stale and the strippers have sexually transmitted diseases. +3.Pirates are "absolute divine beings" and the original Pastafarians. +4.At the time of creation, the flying noodle god first created mountains, trees, and a "dwarf" +5.Every Friday is a holy day and a rest day, and believers can ask employers to rest on that basis. +6.According to these beliefs, the Monster's intoxication was the cause for a flawed Earth. Furthermore, according to Pastafarianism, all evidence for evolution was planted by the Flying Spaghetti Monster in an effort to test the faith of Pastafariansparodying certain biblical literalists. When scientific measurements such as radiocarbon dating are taken, the Flying Spaghetti Monster "is there changing the results with His Noodly Appendage". + +*/ \ No newline at end of file diff --git a/ERC20 Tokens/FavorToken.sol b/ERC20 Tokens/FavorToken.sol new file mode 100644 index 0000000..f76f845 --- /dev/null +++ b/ERC20 Tokens/FavorToken.sol @@ -0,0 +1,1363 @@ +pragma solidity ^0.5.5; /* + + + ___________________________________________________________________ + _ _ ______ + | | / / / + --|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) + __/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + ███████╗ █████╗ ██╗ ██╗ ██████╗ ██████╗ ████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ + ██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔══██╗ ╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗ ██║ + █████╗ ███████║██║ ██║██║ ██║██████╔╝ ██║ ██║ ██║█████╔╝ █████╗ ██╔██╗ ██║ + ██╔══╝ ██╔══██║╚██╗ ██╔╝██║ ██║██╔══██╗ ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║ + ██║ ██║ ██║ ╚████╔╝ ╚██████╔╝██║ ██║ ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║ + ╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ + + + +=== 'Favor Token' contract with following features === + => ERC20 Compliance + => EIP1613 Compliance - https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1613.md + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => Burnable + => Non-minting + => Air-Dropdrop (active) + => User wallet freeze function + + +======================= Quick Stats =================== + => Name : Favor Token + => Symbol : FVR + => Total supply: 70,000,000 (70 Million) + => Decimals : 3 + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + + +------------------------------------------------------------------- + Copyright (c) 2020 onwards Favor Token Inc. ( https://favortoken.io ) + Contract designed with ❤ by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + + + + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address public owner; + address internal newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + emit OwnershipTransferred(address(0), owner); + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +library LibBytes { + + using LibBytes for bytes; + + /// @dev Gets the memory address for a byte array. + /// @param input Byte array to lookup. + /// @return memoryAddress Memory address of byte array. This + /// points to the header of the byte array which contains + /// the length. + function rawAddress(bytes memory input) + internal + pure + returns (uint256 memoryAddress) + { + assembly { + memoryAddress := input + } + return memoryAddress; + } + + /// @dev Gets the memory address for the contents of a byte array. + /// @param input Byte array to lookup. + /// @return memoryAddress Memory address of the contents of the byte array. + function contentAddress(bytes memory input) + internal + pure + returns (uint256 memoryAddress) + { + assembly { + memoryAddress := add(input, 32) + } + return memoryAddress; + } + + /// @dev Copies `length` bytes from memory location `source` to `dest`. + /// @param dest memory address to copy bytes to. + /// @param source memory address to copy bytes from. + /// @param length number of bytes to copy. + function memCopy( + uint256 dest, + uint256 source, + uint256 length + ) + internal + pure + { + if (length < 32) { + // Handle a partial word by reading destination and masking + // off the bits we are interested in. + // This correctly handles overlap, zero lengths and source == dest + assembly { + let mask := sub(exp(256, sub(32, length)), 1) + let s := and(mload(source), not(mask)) + let d := and(mload(dest), mask) + mstore(dest, or(s, d)) + } + } else { + // Skip the O(length) loop when source == dest. + if (source == dest) { + return; + } + + // For large copies we copy whole words at a time. The final + // word is aligned to the end of the range (instead of after the + // previous) to handle partial words. So a copy will look like this: + // + // #### + // #### + // #### + // #### + // + // We handle overlap in the source and destination range by + // changing the copying direction. This prevents us from + // overwriting parts of source that we still need to copy. + // + // This correctly handles source == dest + // + if (source > dest) { + assembly { + // We subtract 32 from `sEnd` and `dEnd` because it + // is easier to compare with in the loop, and these + // are also the addresses we need for copying the + // last bytes. + length := sub(length, 32) + let sEnd := add(source, length) + let dEnd := add(dest, length) + + // Remember the last 32 bytes of source + // This needs to be done here and not after the loop + // because we may have overwritten the last bytes in + // source already due to overlap. + let last := mload(sEnd) + + // Copy whole words front to back + // Note: the first check is always true, + // this could have been a do-while loop. + // solhint-disable-next-line no-empty-blocks + for {} lt(source, sEnd) {} { + mstore(dest, mload(source)) + source := add(source, 32) + dest := add(dest, 32) + } + + // Write the last 32 bytes + mstore(dEnd, last) + } + } else { + assembly { + // We subtract 32 from `sEnd` and `dEnd` because those + // are the starting points when copying a word at the end. + length := sub(length, 32) + let sEnd := add(source, length) + let dEnd := add(dest, length) + + // Remember the first 32 bytes of source + // This needs to be done here and not after the loop + // because we may have overwritten the first bytes in + // source already due to overlap. + let first := mload(source) + + // Copy whole words back to front + // We use a signed comparisson here to allow dEnd to become + // negative (happens when source and dest < 32). Valid + // addresses in local memory will never be larger than + // 2**255, so they can be safely re-interpreted as signed. + // Note: the first check is always true, + // this could have been a do-while loop. + // solhint-disable-next-line no-empty-blocks + for {} slt(dest, dEnd) {} { + mstore(dEnd, mload(sEnd)) + sEnd := sub(sEnd, 32) + dEnd := sub(dEnd, 32) + } + + // Write the first 32 bytes + mstore(dest, first) + } + } + } + } + + /// @dev Returns a slices from a byte array. + /// @param b The byte array to take a slice from. + /// @param from The starting index for the slice (inclusive). + /// @param to The final index for the slice (exclusive). + /// @return result The slice containing bytes at indices [from, to) + function slice( + bytes memory b, + uint256 from, + uint256 to + ) + internal + pure + returns (bytes memory result) + { + require( + from <= to, + "FROM_LESS_THAN_TO_REQUIRED" + ); + require( + to <= b.length, + "TO_LESS_THAN_LENGTH_REQUIRED" + ); + + // Create a new bytes structure and copy contents + result = new bytes(to - from); + memCopy( + result.contentAddress(), + b.contentAddress() + from, + result.length); + return result; + } + + /// @dev Returns a slice from a byte array without preserving the input. + /// @param b The byte array to take a slice from. Will be destroyed in the process. + /// @param from The starting index for the slice (inclusive). + /// @param to The final index for the slice (exclusive). + /// @return result The slice containing bytes at indices [from, to) + /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. + function sliceDestructive( + bytes memory b, + uint256 from, + uint256 to + ) + internal + pure + returns (bytes memory result) + { + require( + from <= to, + "FROM_LESS_THAN_TO_REQUIRED" + ); + require( + to < b.length, + "TO_LESS_THAN_LENGTH_REQUIRED" + ); + + // Create a new bytes structure around [from, to) in-place. + assembly { + result := add(b, from) + mstore(result, sub(to, from)) + } + return result; + } + + /// @dev Pops the last byte off of a byte array by modifying its length. + /// @param b Byte array that will be modified. + /// @return The byte that was popped off. + function popLastByte(bytes memory b) + internal + pure + returns (bytes1 result) + { + require( + b.length > 0, + "GREATER_THAN_ZERO_LENGTH_REQUIRED" + ); + + // Store last byte. + result = b[b.length - 1]; + + assembly { + // Decrement length of byte array. + let newLen := sub(mload(b), 1) + mstore(b, newLen) + } + return result; + } + + /// @dev Pops the last 20 bytes off of a byte array by modifying its length. + /// @param b Byte array that will be modified. + /// @return The 20 byte address that was popped off. + function popLast20Bytes(bytes memory b) + internal + pure + returns (address result) + { + require( + b.length >= 20, + "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" + ); + + // Store last 20 bytes. + result = readAddress(b, b.length - 20); + + assembly { + // Subtract 20 from byte array length. + let newLen := sub(mload(b), 20) + mstore(b, newLen) + } + return result; + } + + /// @dev Tests equality of two byte arrays. + /// @param lhs First byte array to compare. + /// @param rhs Second byte array to compare. + /// @return True if arrays are the same. False otherwise. + function equals( + bytes memory lhs, + bytes memory rhs + ) + internal + pure + returns (bool equal) + { + // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. + // We early exit on unequal lengths, but keccak would also correctly + // handle this. + return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); + } + + /// @dev Reads an address from a position in a byte array. + /// @param b Byte array containing an address. + /// @param index Index in byte array of address. + /// @return address from byte array. + function readAddress( + bytes memory b, + uint256 index + ) + internal + pure + returns (address result) + { + require( + b.length >= index + 20, // 20 is length of address + "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" + ); + + // Add offset to index: + // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) + // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) + index += 20; + + // Read address from array memory + assembly { + // 1. Add index to address of bytes array + // 2. Load 32-byte word from memory + // 3. Apply 20-byte mask to obtain address + result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) + } + return result; + } + + /// @dev Writes an address into a specific position in a byte array. + /// @param b Byte array to insert address into. + /// @param index Index in byte array of address. + /// @param input Address to put into byte array. + function writeAddress( + bytes memory b, + uint256 index, + address input + ) + internal + pure + { + require( + b.length >= index + 20, // 20 is length of address + "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" + ); + + // Add offset to index: + // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) + // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) + index += 20; + + // Store address into array memory + assembly { + // The address occupies 20 bytes and mstore stores 32 bytes. + // First fetch the 32-byte word where we'll be storing the address, then + // apply a mask so we have only the bytes in the word that the address will not occupy. + // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. + + // 1. Add index to address of bytes array + // 2. Load 32-byte word from memory + // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address + let neighbors := and( + mload(add(b, index)), + 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 + ) + + // Make sure input address is clean. + // (Solidity does not guarantee this) + input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) + + // Store the neighbors and address into memory + mstore(add(b, index), xor(input, neighbors)) + } + } + + /// @dev Reads a bytes32 value from a position in a byte array. + /// @param b Byte array containing a bytes32 value. + /// @param index Index in byte array of bytes32 value. + /// @return bytes32 value from byte array. + function readBytes32( + bytes memory b, + uint256 index + ) + internal + pure + returns (bytes32 result) + { + require( + b.length >= index + 32, + "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" + ); + + // Arrays are prefixed by a 256 bit length parameter + index += 32; + + // Read the bytes32 from array memory + assembly { + result := mload(add(b, index)) + } + return result; + } + + /// @dev Writes a bytes32 into a specific position in a byte array. + /// @param b Byte array to insert into. + /// @param index Index in byte array of . + /// @param input bytes32 to put into byte array. + function writeBytes32( + bytes memory b, + uint256 index, + bytes32 input + ) + internal + pure + { + require( + b.length >= index + 32, + "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" + ); + + // Arrays are prefixed by a 256 bit length parameter + index += 32; + + // Read the bytes32 from array memory + assembly { + mstore(add(b, index), input) + } + } + + /// @dev Reads a uint256 value from a position in a byte array. + /// @param b Byte array containing a uint256 value. + /// @param index Index in byte array of uint256 value. + /// @return uint256 value from byte array. + function readUint256( + bytes memory b, + uint256 index + ) + internal + pure + returns (uint256 result) + { + return uint256(readBytes32(b, index)); + } + + /// @dev Writes a uint256 into a specific position in a byte array. + /// @param b Byte array to insert into. + /// @param index Index in byte array of . + /// @param input uint256 to put into byte array. + function writeUint256( + bytes memory b, + uint256 index, + uint256 input + ) + internal + pure + { + writeBytes32(b, index, bytes32(input)); + } + + /// @dev Reads an unpadded bytes4 value from a position in a byte array. + /// @param b Byte array containing a bytes4 value. + /// @param index Index in byte array of bytes4 value. + /// @return bytes4 value from byte array. + function readBytes4( + bytes memory b, + uint256 index) + internal + pure + returns (bytes4 result) + { + require( + b.length >= index + 4, + "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" + ); + assembly { + result := mload(add(b, 32)) + // Solidity does not require us to clean the trailing bytes. + // We do it anyway + result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) + } + return result; + } + + /// @dev Reads nested bytes from a specific position. + /// @dev NOTE: the returned value overlaps with the input value. + /// Both should be treated as immutable. + /// @param b Byte array containing nested bytes. + /// @param index Index of nested bytes. + /// @return result Nested bytes. + function readBytesWithLength( + bytes memory b, + uint256 index + ) + internal + pure + returns (bytes memory result) + { + // Read length of nested bytes + uint256 nestedBytesLength = readUint256(b, index); + index += 32; + + // Assert length of is valid, given + // length of nested bytes + require( + b.length >= index + nestedBytesLength, + "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" + ); + + // Return a pointer to the byte array as it exists inside `b` + assembly { + result := add(b, index) + } + return result; + } + + /// @dev Inserts bytes at a specific position in a byte array. + /// @param b Byte array to insert into. + /// @param index Index in byte array of . + /// @param input bytes to insert. + function writeBytesWithLength( + bytes memory b, + uint256 index, + bytes memory input + ) + internal + pure + { + // Assert length of is valid, given + // length of input + require( + b.length >= index + 32 + input.length, // 32 bytes to store length + "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" + ); + + // Copy into + memCopy( + b.contentAddress() + index, + input.rawAddress(), // includes length of + input.length + 32 // +32 bytes to store length + ); + } + + /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. + /// @param dest Byte array that will be overwritten with source bytes. + /// @param source Byte array to copy onto dest bytes. + function deepCopyBytes( + bytes memory dest, + bytes memory source + ) + internal + pure + { + uint256 sourceLen = source.length; + // Dest length must be >= source length, or some bytes would not be copied. + require( + dest.length >= sourceLen, + "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED" + ); + memCopy( + dest.contentAddress(), + source.contentAddress(), + sourceLen + ); + } +} + + + + +contract IRelayHub { + // Relay management + + // Add stake to a relay and sets its unstakeDelay. + // If the relay does not exist, it is created, and the caller + // of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay + // cannot be its own owner. + // All Ether in this function call will be added to the relay's stake. + // Its unstake delay will be assigned to unstakeDelay, but the new value must be greater or equal to the current one. + // Emits a Staked event. + function stake(address relayaddr, uint256 unstakeDelay) external payable; + + // Emited when a relay's stake or unstakeDelay are increased + event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay); + + // Registers the caller as a relay. + // The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA). + // Emits a RelayAdded event. + // This function can be called multiple times, emitting new RelayAdded events. Note that the received transactionFee + // is not enforced by relayCall. + function registerRelay(uint256 transactionFee, string memory url) public; + + // Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out RelayRemoved + // events) lets a client discover the list of available relays. + event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url); + + // Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. Can only be called by + // the owner of the relay. After the relay's unstakeDelay has elapsed, unstake will be callable. + // Emits a RelayRemoved event. + function removeRelayByOwner(address relay) public; + + // Emitted when a relay is removed (deregistered). unstakeTime is the time when unstake will be callable. + event RelayRemoved(address indexed relay, uint256 unstakeTime); + + // Deletes the relay from the system, and gives back its stake to the owner. Can only be called by the relay owner, + // after unstakeDelay has elapsed since removeRelayByOwner was called. + // Emits an Unstaked event. + function unstake(address relay) public; + + // Emitted when a relay is unstaked for, including the returned stake. + event Unstaked(address indexed relay, uint256 stake); + + // States a relay can be in + enum RelayState { + Unknown, // The relay is unknown to the system: it has never been staked for + Staked, // The relay has been staked for, but it is not yet active + Registered, // The relay has registered itself, and is active (can relay calls) + Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake + } + + // Returns a relay's status. Note that relays can be deleted when unstaked or penalized. + function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state); + + // Balance management + + // Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only + // be withdrawn by the contract itself, by callingn withdraw. + // Emits a Deposited event. + function depositFor(address target) public payable; + + // Emitted when depositFor is called, including the amount and account that was funded. + event Deposited(address indexed recipient, address indexed from, uint256 amount); + + // Returns an account's deposits. These can be either a contnract's funds, or a relay owner's revenue. + function balanceOf(address target) external view returns (uint256); + + // Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and + // contracts can also use it to reduce their funding. + // Emits a Withdrawn event. + function withdraw(uint256 amount, address payable dest) public; + + // Emitted when an account withdraws funds from RelayHub. + event Withdrawn(address indexed account, address indexed dest, uint256 amount); + + // Relaying + + // Check if the RelayHub will accept a relayed operation. Multiple things must be true for this to happen: + // - all arguments must be signed for by the sender (from) + // - the sender's nonce must be the current one + // - the recipient must accept this transaction (via acceptRelayedCall) + // Returns a PreconditionCheck value (OK when the transaction can be relayed), or a recipient-specific error code if + // it returns one in acceptRelayedCall. + function canRelay( + address relay, + address from, + address to, + bytes memory encodedFunction, + uint256 transactionFee, + uint256 gasPrice, + uint256 gasLimit, + uint256 nonce, + bytes memory signature, + bytes memory approvalData + ) public view returns (uint256 status, bytes memory recipientContext); + + // Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values. + enum PreconditionCheck { + OK, // All checks passed, the call can be relayed + WrongSignature, // The transaction to relay is not signed by requested sender + WrongNonce, // The provided nonce has already been used by the sender + AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall + InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code + } + + // Relays a transaction. For this to suceed, multiple conditions must be met: + // - canRelay must return PreconditionCheck.OK + // - the sender must be a registered relay + // - the transaction's gas price must be larger or equal to the one that was requested by the sender + // - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the + // recipient) use all gas available to them + // - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is + // spent) + // + // If all conditions are met, the call will be relayed and the recipient charged. preRelayedCall, the encoded + // function and postRelayedCall will be called in order. + // + // Arguments: + // - from: the client originating the request + // - recipient: the target IRelayRecipient contract + // - encodedFunction: the function call to relay, including data + // - transactionFee: fee (%) the relay takes over actual gas cost + // - gasPrice: gas price the client is willing to pay + // - gasLimit: gas to forward when calling the encoded function + // - nonce: client's nonce + // - signature: client's signature over all previous params, plus the relay and RelayHub addresses + // - approvalData: dapp-specific data forwared to acceptRelayedCall. This value is *not* verified by the Hub, but + // it still can be used for e.g. a signature. + // + // Emits a TransactionRelayed event. + function relayCall( + address from, + address to, + bytes memory encodedFunction, + uint256 transactionFee, + uint256 gasPrice, + uint256 gasLimit, + uint256 nonce, + bytes memory signature, + bytes memory approvalData + ) public; + + // Emitted when an attempt to relay a call failed. This can happen due to incorrect relayCall arguments, or the + // recipient not accepting the relayed call. The actual relayed call was not executed, and the recipient not charged. + // The reason field contains an error code: values 1-10 correspond to PreconditionCheck entries, and values over 10 + // are custom recipient error codes returned from acceptRelayedCall. + event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason); + + // Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be + // indicated in the status field. + // Useful when monitoring a relay's operation and relayed calls to a contract. + // Charge is the ether value deducted from the recipient's balance, paid to the relay's owner. + event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge); + + // Reason error codes for the TransactionRelayed event + enum RelayCallStatus { + OK, // The transaction was successfully relayed and execution successful - never included in the event + RelayedCallFailed, // The transaction was relayed, but the relayed call failed + PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting + PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting + RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing + } + + // Returns how much gas should be forwarded to a call to relayCall, in order to relay a transaction that will spend + // up to relayedCallStipend gas. + function requiredGas(uint256 relayedCallStipend) public view returns (uint256); + + // Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee. + function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256); + + // Relay penalization. Any account can penalize relays, removing them from the system immediately, and rewarding the + // reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it + // still loses half of its stake. + + // Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and + // different data (gas price, gas limit, etc. may be different). The (unsigned) transaction data and signature for + // both transactions must be provided. + function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public; + + // Penalize a relay that sent a transaction that didn't target RelayHub's registerRelay or relayCall. + function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public; + + event Penalized(address indexed relay, address sender, uint256 amount); + + function getNonce(address from) view external returns (uint256); +} + + + + + +contract IRelayRecipient { + + /** + * return the relayHub of this contract. + */ + function getHubAddr() public view returns (address); + + /** + * return the contract's balance on the RelayHub. + * can be used to determine if the contract can pay for incoming calls, + * before making any. + */ + function getRecipientBalance() public view returns (uint256); + + /* + * Called by Relay (and RelayHub), to validate if this recipient accepts this call. + * Note: Accepting this call means paying for the tx whether the relayed call reverted or not. + * + * @return "0" if the the contract is willing to accept the charges from this sender, for this function call. + * any other value is a failure. actual value is for diagnostics only. + * ** Note: values below 10 are reserved by canRelay + + * @param relay the relay that attempts to relay this function call. + * the contract may restrict some encoded functions to specific known relays. + * @param from the sender (signer) of this function call. + * @param encodedFunction the encoded function call (without any ethereum signature). + * the contract may check the method-id for valid methods + * @param gasPrice - the gas price for this transaction + * @param transactionFee - the relay compensation (in %) for this transaction + * @param signature - sender's signature over all parameters except approvalData + * @param approvalData - extra dapp-specific data (e.g. signature from trusted party) + */ + function acceptRelayedCall( + address relay, + address from, + bytes calldata encodedFunction, + uint256 transactionFee, + uint256 gasPrice, + uint256 gasLimit, + uint256 nonce, + bytes calldata approvalData, + uint256 maxPossibleCharge + ) + external + view + returns (uint256, bytes memory); + + /* + * modifier to be used by recipients as access control protection for preRelayedCall & postRelayedCall + */ + modifier relayHubOnly() { + require(msg.sender == getHubAddr(),"Function can only be called by RelayHub"); + _; + } + + /** this method is called before the actual relayed function call. + * It may be used to charge the caller before (in conjuction with refunding him later in postRelayedCall for example). + * the method is given all parameters of acceptRelayedCall and actual used gas. + * + * + *** NOTICE: if this method modifies the contract's state, it must be protected with access control i.e. require msg.sender == getHubAddr() + * + * + * Revert in this functions causes a revert of the client's relayed call but not in the entire transaction + * (that is, the relay will still get compensated) + */ + function preRelayedCall(bytes calldata context) external returns (bytes32); + + /** this method is called after the actual relayed function call. + * It may be used to record the transaction (e.g. charge the caller by some contract logic) for this call. + * the method is given all parameters of acceptRelayedCall, and also the success/failure status and actual used gas. + * + * + *** NOTICE: if this method modifies the contract's state, it must be protected with access control i.e. require msg.sender == getHubAddr() + * + * + * @param success - true if the relayed call succeeded, false if it reverted + * @param actualCharge - estimation of how much the recipient will be charged. This information may be used to perform local booking and + * charge the sender for this call (e.g. in tokens). + * @param preRetVal - preRelayedCall() return value passed back to the recipient + * + * Revert in this functions causes a revert of the client's relayed call but not in the entire transaction + * (that is, the relay will still get compensated) + */ + function postRelayedCall(bytes calldata context, bool success, uint actualCharge, bytes32 preRetVal) external; + +} + + + + +contract RelayRecipient is IRelayRecipient, IRelayHub { + + using LibBytes for bytes; + + IRelayHub private relayHub; // The IRelayHub singleton which is allowed to call us + + function getHubAddr() public view returns (address) { + return address(relayHub); + } + + /** + * Initialize the RelayHub of this contract. + * Must be called at least once (e.g. from the constructor), so that the contract can accept relayed calls. + * For ownable contracts, there should be a method to update the RelayHub, in case a new hub is deployed (since + * the RelayHub itself is not upgradeable) + * Otherwise, the contract might be locked on a dead hub, with no relays. + */ + function setRelayHub(IRelayHub _rhub) internal { + relayHub = _rhub; + } + + function getRelayHub() internal view returns (IRelayHub) { + return relayHub; + } + + /** + * return the balance of this contract. + * Note that this method will revert on configuration error (invalid relay address) + */ + function getRecipientBalance() public view returns (uint) { + return getRelayHub().balanceOf(address(this)); + } + + function getSenderFromData(address origSender, bytes memory msgData) public view returns (address) { + address sender = origSender; + if (origSender == getHubAddr()) { + // At this point we know that the sender is a trusted IRelayHub, so we trust that the last bytes of msg.data are the verified sender address. + // extract sender address from the end of msg.data + sender = LibBytes.readAddress(msgData, msgData.length - 20); + } + return sender; + } + + /** + * return the sender of this call. + * if the call came through the valid RelayHub, return the original sender. + * otherwise, return `msg.sender` + * should be used in the contract anywhere instead of msg.sender + */ + function getSender() public view returns (address) { + return getSenderFromData(msg.sender, msg.data); + } + + function getMessageData() public view returns (bytes memory) { + bytes memory origMsgData = msg.data; + if (msg.sender == getHubAddr()) { + // At this point we know that the sender is a trusted IRelayHub, so we trust that the last bytes of msg.data are the verified sender address. + // extract original message data from the start of msg.data + origMsgData = new bytes(msg.data.length - 20); + for (uint256 i = 0; i < origMsgData.length; i++) + { + origMsgData[i] = msg.data[i]; + } + } + return origMsgData; + } +} + + +//****************************************************************************// +//--------------------- MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract FavotToken is owned, RelayRecipient { + + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string constant private _name = "Favor Token"; + string constant private _symbol = "FVR"; + uint256 constant private _decimals = 3; + uint256 private _totalSupply = 70000000 * (10**_decimals); //70 million tokens + bool public safeguard; + + + // This creates a mapping with all data storage + mapping (address => uint256) private _balanceOf; + mapping (address => mapping (address => uint256)) private _allowance; + mapping (address => bool) public frozenAccount; + + mapping (address => bool) public FavorTokenUser; + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenAccounts(address target, bool frozen); + + // This will log approval of token Transfer + event Approval(address indexed from, address indexed spender, uint256 value); + + + + function implementRealyHub(address hubAddress) public onlyOwner returns(bool) + { + setRelayHub(IRelayHub(hubAddress)); + return true; + } + + function acceptRelayedCall(address relay, address from, bytes calldata encodedFunction, + uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, + bytes calldata approvalData, uint256 maxPossibleCharge) + external view returns (uint256, bytes memory) { + + // we simply trust all our known users. + if ( !FavorTokenUser[from] ) return (10, "unknown user"); + return (0,""); + } + + // If need this pre-post can be written + function preRelayedCall(bytes calldata context) relayHubOnly external returns (bytes32) { + return 0; + } + + function postRelayedCall(bytes calldata context, bool success, uint actualCharge, bytes32 preRetVal) relayHubOnly external { + + } + + function addFavorTokenUser(address _newUser) public onlyOwner returns (bool) + { + FavorTokenUser[_newUser] = true; + + return true; + } + + function removeFavorTokenUser(address _user) public onlyOwner returns (bool) + { + FavorTokenUser[_user] = false; + + return true; + } + + + + /*====================================== + = STANDARD ERC20 FUNCTIONS = + ======================================*/ + + /** + * Returns name of token + */ + function name() public pure returns(string memory){ + return _name; + } + + /** + * Returns symbol of token + */ + function symbol() public pure returns(string memory){ + return _symbol; + } + + /** + * Returns decimals of token + */ + function decimals() public pure returns(uint256){ + return _decimals; + } + + /** + * Returns totalSupply of token. + */ + function totalSupply() public view returns (uint256) { + return _totalSupply; + } + + /** + * Returns balance of token + */ + function balanceOf(address user) public view returns(uint256){ + return _balanceOf[user]; + } + + /** + * Returns allowance of token + */ + function allowance(address owner, address spender) public view returns (uint256) { + return _allowance[owner][spender]; + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguard); + require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + + // overflow and undeflow checked by SafeMath Library + _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender + _balanceOf[_to] = _balanceOf[_to].add(_value); // Add to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require ( FavorTokenUser[ getSender() ] ); + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + //checking of allowance and token value is done by SafeMath + require(!safeguard); + require ( FavorTokenUser[ getSender() ] ); + _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + require ( FavorTokenUser[ getSender() ] ); + _allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + /** + * @dev Increase the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To increment + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * Emits an Approval event. + * @param spender The address which will spend the funds. + * @param value The amount of tokens to increase the allowance by. + */ + function increase_allowance(address spender, uint256 value) public returns (bool) { + require(!safeguard); + require ( FavorTokenUser[ getSender() ] ); + require(spender != address(0)); + _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(value); + emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); + return true; + } + + /** + * @dev Decrease the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To decrement + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * Emits an Approval event. + * @param spender The address which will spend the funds. + * @param value The amount of tokens to decrease the allowance by. + */ + function decrease_allowance(address spender, uint256 value) public returns (bool) { + require(!safeguard); + require ( FavorTokenUser[ getSender() ] ); + require(spender != address(0)); + _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(value); + emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); + return true; + } + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + constructor() public{ + //sending all the tokens to Owner + _balanceOf[owner] = _totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, _totalSupply); + + } + + + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + require ( FavorTokenUser[ getSender() ] ); + //checking of enough token balance is done by SafeMath + _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); // Subtract from the sender + _totalSupply = _totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenAccounts(target, freeze); + } + + + /** + * Owner can transfer tokens from contract to owner address + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + + /*************************************/ + /* Section for User Air drop */ + /*************************************/ + /** + * Run an ACTIVE Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public onlyOwner returns(bool) { + uint256 totalAddresses = recipients.length; + require(totalAddresses <= 150,"Too many recipients"); + for(uint64 i = 0; i < totalAddresses; i++) + { + //This will loop through all the recipients and send them the specified tokens + //Input data validation is unncessary, as that is done by SafeMath and which also saves some gas. + transfer(recipients[i], tokenAmount[i]); + } + return true; + } + + + + + + + +} diff --git a/ERC20 Tokens/IPUX token.sol b/ERC20 Tokens/IPUX token.sol new file mode 100644 index 0000000..18ab14b --- /dev/null +++ b/ERC20 Tokens/IPUX token.sol @@ -0,0 +1,371 @@ +pragma solidity 0.5.2; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + .----------------. .----------------. .----------------. .----------------. +| .--------------. | | .--------------. | | .--------------. | | .--------------. | +| | _____ | | | | ______ | | | | _____ _____ | | | | ____ ____ | | +| | |_ _| | | | | |_ __ \ | | | ||_ _||_ _|| | | | |_ _||_ _| | | +| | | | | | | | | |__) | | | | | | | | | | | | | \ \ / / | | +| | | | | | | | | ___/ | | | | | ' ' | | | | | > `' < | | +| | _| |_ | | | | _| |_ | | | | \ `--' / | | | | _/ /'`\ \_ | | +| | |_____| | | | | |_____| | | | | `.__.' | | | | |____||____| | | +| | | | | | | | | | | | | | | | +| '--------------' | | '--------------' | | '--------------' | | '--------------' | + '----------------' '----------------' '----------------' '----------------' + + +// ---------------------------------------------------------------------------- +// 'IPUX' Token contract with following features +// => ERC20 Compliance +// => Higher degree of control by owner - safeguard functionality +// => selfdestruct ability by owner +// => SafeMath implementation +// => Burnable and minting +// => air drop +// +// Name : IPUX token +// Symbol : IPUX +// Total supply: 160,000,000 (160 Million) +// Decimals : 18 +// +// Copyright (c) 2019 TradeWeIPUX Limited ( https://ipux.io ) +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- + +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// + /** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ + library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + } + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + + contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } + } + + + +//***************************************************************// +//------------------ ERC20 Standard Template -------------------// +//***************************************************************// + + contract TokenERC20 { + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint256 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + address public icoContractAddress; + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor ( + uint256 initialSupply, + string memory tokenName, + string memory tokenSymbol, + address _icoContractAddress + ) public { + + totalSupply = initialSupply * (10**decimals); // Update total supply with the decimal amount + uint256 tokensReserved = 96000000 * (10**decimals); // 96 Million tokens will remain in the contract + uint256 tokensCrowdsale = 64000000 * (10**decimals);// 64 million tokens will be sent to ICO contract for public ICO + + balanceOf[address(this)] = tokensReserved; + balanceOf[_icoContractAddress] = tokensCrowdsale; + + name = tokenName; // Set the name for display purposes + symbol = tokenSymbol; // Set the symbol for display purposes + icoContractAddress = _icoContractAddress; // set ICO contract address + + emit Transfer(address(0), address(this), tokensReserved);// Emit event to log this transaction + emit Transfer(address(0), _icoContractAddress, tokensCrowdsale);// Emit event to log this transaction + + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != address(0x0)); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + + } + +//****************************************************************************// +//--------------------- IPUX MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + + contract IPUXtoken is owned, TokenERC20 { + + + /*********************************/ + /* Code for the ERC20 IPUX Token */ + /*********************************/ + + /* Public variables of the token */ + string private tokenName = "IPUX Token"; + string private tokenSymbol = "IPUX"; + uint256 private initialSupply = 160000000; //160 Million + + + + /* Records for the fronzen accounts */ + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with initial supply tokens to the creator of the contract */ + constructor (address icoContractAddress) TokenERC20(initialSupply, tokenName, tokenSymbol, icoContractAddress) public { + + } + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead + require (balanceOf[_from] >= _value); // Check if the sender has enough + require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + /// @notice Create `mintedAmount` tokens and send it to `target` + /// @param target Address to receive the tokens + /// @param mintedAmount the amount of tokens it will receive + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + balanceOf[target] = balanceOf[target].add(mintedAmount); + totalSupply = totalSupply.add(mintedAmount); + emit Transfer(address(0), target, mintedAmount); + } + + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + //selfdestruct function. just in case owner decided to destruct this contract. + function destructContract()onlyOwner public{ + selfdestruct(owner); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + /********************************/ + /* Code for the Air drop */ + /********************************/ + + /** + * Run an Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdrop(address[] memory recipients,uint tokenAmount) public onlyOwner { + uint256 addressCount = recipients.length; + require(addressCount <= 150); + for(uint i = 0; i < addressCount; i++) + { + //This will loop through all the recipients and send them the specified tokens + _transfer(address(this), recipients[i], tokenAmount); + } + } + +} diff --git a/ERC20 Tokens/SE7EN.sol b/ERC20 Tokens/SE7EN.sol new file mode 100644 index 0000000..16ff682 --- /dev/null +++ b/ERC20 Tokens/SE7EN.sol @@ -0,0 +1,549 @@ +pragma solidity 0.5.0; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + .----------------. .----------------. .----------------. .----------------. .-----------------. +| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. | +| | _______ | || | _________ | || | _______ | || | _________ | || | ____ _____ | | +| | / ___ | | || | |_ ___ | | || | | ___ | | || | |_ ___ | | || ||_ \|_ _| | | +| | | (__ \_| | || | | |_ \_| | || | |_/ / / | || | | |_ \_| | || | | \ | | | | +| | '.___`-. | || | | _| _ | || | / / | || | | _| _ | || | | |\ \| | | | +| | |`\____) | | || | _| |___/ | | || | / / | || | _| |___/ | | || | _| |_\ |_ | | +| | |_______.' | || | |_________| | || | /_/ | || | |_________| | || ||_____|\____| | | +| | | || | | || | | || | | || | | | +| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' | + '----------------' '----------------' '----------------' '----------------' '----------------' + + +// ---------------------------------------------------------------------------- +// 'se7en' Token contract with following features +// => In-built ICO functionality +// => ERC20 Compliance +// => Higher control of ICO by owner +// => selfdestruct functionality +// => SafeMath implementation +// => Air-drop +// => User whitelisting +// => Minting/burning by owner +// +// Name : se7en +// Symbol : S7N +// Total supply: 74,243,687,134 +// Reserved coins for ICO: 7,424,368,713 +// Decimals : 18 +// +// Copyright (c) 2018 XSe7en Social Media Inc. ( https://se7en.social ) +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- + +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// + /** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ + library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + } + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + + contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } + } + + interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } + + +//***************************************************************// +//------------------ ERC20 Standard Template -------------------// +//***************************************************************// + + contract TokenERC20 { + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply; + uint256 public reservedForICO; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor ( + uint256 initialSupply, + uint256 allocatedForICO, + string memory tokenName, + string memory tokenSymbol + ) public { + totalSupply = initialSupply.mul(1 ether); // Update total supply with the decimal amount + reservedForICO = allocatedForICO.mul(1 ether); // Tokens reserved For ICO + balanceOf[address(this)] = reservedForICO; // 7,424,368,713 Tokens will remain in the contract + balanceOf[msg.sender]=totalSupply.sub(reservedForICO); // Rest of tokens will be sent to owner + name = tokenName; // Set the name for display purposes + symbol = tokenSymbol; // Set the symbol for display purposes + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != address(0x0)); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + + /** + * Set allowance for other address and notify + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + * @param _extraData some extra information to send to the approved contract + */ + function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) + public + returns (bool success) { + require(!safeguard); + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, address(this), _extraData); + return true; + } + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + + } + +//************************************************************************// +//--------------------- SE7EN MAIN CODE STARTS HERE ---------------------// +//************************************************************************// + + contract se7en is owned, TokenERC20 { + + /*************************************/ + /* User whitelisting functionality */ + /*************************************/ + bool public whitelistingStatus = false; + mapping (address => bool) public whitelisted; + + /** + * Change whitelisting status on or off + * + * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. + */ + function changeWhitelistingStatus() onlyOwner public{ + if (whitelistingStatus == false){ + whitelistingStatus = true; + } + else{ + whitelistingStatus = false; + } + } + + /** + * Whitelist any user address - only Owner can do this + * + * It will add user address in whitelisted mapping + */ + function whitelistUser(address userAddress) onlyOwner public{ + require(whitelistingStatus == true); + require(userAddress != address(0x0)); + whitelisted[userAddress] = true; + } + + /** + * Whitelist Many user address at once - only Owner can do this + * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack + * It will add user address in whitelisted mapping + */ + function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ + require(whitelistingStatus == true); + uint256 addressCount = userAddresses.length; + require(addressCount <= 150); + for(uint256 i = 0; i < addressCount; i++){ + require(userAddresses[i] != address(0x0)); + whitelisted[userAddresses[i]] = true; + } + } + + + + /********************************/ + /* Code for the ERC20 S7N Token */ + /********************************/ + + /* Public variables of the token */ + string private tokenName = "se7en"; + string private tokenSymbol = "S7N"; + uint256 private initialSupply = 74243687134; + uint256 private allocatedForICO = 7424368713; + + + /* Records for the fronzen accounts */ + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with initial supply tokens to the creator of the contract */ + constructor () TokenERC20(initialSupply, allocatedForICO, tokenName, tokenSymbol) public {} + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead + require (balanceOf[_from] >= _value); // Check if the sender has enough + require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + /// @notice Create `mintedAmount` tokens and send it to `target` + /// @param target Address to receive the tokens + /// @param mintedAmount the amount of tokens it will receive + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + balanceOf[target] = balanceOf[target].add(mintedAmount); + totalSupply = totalSupply.add(mintedAmount); + emit Transfer(address(0x0), address(this), mintedAmount); + emit Transfer(address(this), target, mintedAmount); + } + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + /******************************/ + /* Code for the S7N Crowdsale */ + /******************************/ + + /* TECHNICAL SPECIFICATIONS: + + => ICO Phases details : + Pre Sale - Dec 16 - Dec 31, 2018 (minimum 1 ETH 50% Bonus) + ICO Phase 1 - January 1 - 15, 2019 - 20% Bonus (No minimum or maximum contribution) + ICO Phase 2 - January 16 - 31, 2019 - 10% Bonus (No minimum or maximum contribution) + ICO Phase 3 - February 1 - 28, 2019 - 5% Bonus (No minimum or maximum contribution) + => Token Exchange Rate : 1 ETH = 1298 Tokens (which equivalents to 1 Tokens ≈ 0.00077 ETH) + => Coins reserved for ICO : 7,424,368,713 + + */ + + //public variables for the Crowdsale + //to convert date to timestamp: https://etherauthority.io/tools/timestamp + uint256 public datePreSale = 1544943600 ; // 16 Dec 2018 07:00:00 - GMT + uint256 public dateIcoPhase1 = 1546326000 ; // 01 Jan 2019 07:00:00 - GMT + uint256 public dateIcoPhase2 = 1547622000 ; // 16 Jan 2019 07:00:00 - GMT + uint256 public dateIcoPhase3 = 1549004400 ; // 01 Feb 2019 07:00:00 - GMT + uint256 public dateIcoEnd = 1551398399 ; // 28 Feb 2019 23:59:59 - GMT + uint256 public exchangeRate = 1298; // 1 ETH = 1298 Tokens + uint256 public tokensSold = 0; // how many tokens sold through crowdsale + + //@dev fallback function, only accepts ether if pre-sale or ICO is running or Reject + function () payable external { + require(!safeguard); + require(!frozenAccount[msg.sender]); + require(datePreSale < now && dateIcoEnd > now); + if(whitelistingStatus == true) { require(whitelisted[msg.sender]); } + if(datePreSale < now && dateIcoPhase1 > now){ require(msg.value >= (1 ether)); } + // calculate token amount to be sent + uint256 token = msg.value.mul(exchangeRate); //weiamount * exchangeRate + uint256 finalTokens = token.add(calculatePurchaseBonus(token)); //add bonus if available + tokensSold = tokensSold.add(finalTokens); + _transfer(address(this), msg.sender, finalTokens); //makes the transfers + forwardEherToOwner(); //send Ether to owner + } + + + //calculating purchase bonus + function calculatePurchaseBonus(uint256 token) internal view returns(uint256){ + if(datePreSale < now && now < dateIcoPhase1 ){ + return token.mul(50).div(100); //50% bonus in pre sale + } + else if(dateIcoPhase1 < now && now < dateIcoPhase2 ){ + return token.mul(20).div(100); //20% bonus in ICO phase 1 + } + else if(dateIcoPhase2 < now && now < dateIcoPhase3 ){ + return token.mul(10).div(100); //10% bonus in ICO phase 2 + } + else if(dateIcoPhase3 < now && now < dateIcoEnd ){ + return token.mul(5).div(100); //5% bonus in ICO phase 3 + } + else{ + return 0; //NO BONUS + } + } + + //Automatocally forwards ether from smart contract to owner address + function forwardEherToOwner() internal { + address(owner).transfer(msg.value); + } + + //Function to update an ICO parameter. + //It requires: timestamp of all the dates + //For date to timestamp conversion: https://etherauthority.io/tools/timestamp + //Owner need to make sure the contract has enough tokens for ICO. + //If not enough, then he needs to transfer some tokens into contract addresss from his wallet + //If there are no tokens in smart contract address, then ICO will not work. + //Only thing is required is that all the dates of phases must be in ascending order. + function updateCrowdsale(uint256 datePreSaleNew, uint256 dateIcoPhase1New, uint256 dateIcoPhase2New, uint256 dateIcoPhase3New, uint256 dateIcoEndNew) onlyOwner public { + require(datePreSaleNew < dateIcoPhase1New && dateIcoPhase1New < dateIcoPhase2New); + require(dateIcoPhase2New < dateIcoPhase3New && dateIcoPhase3New < dateIcoEnd); + datePreSale = datePreSaleNew; + dateIcoPhase1 = dateIcoPhase1New; + dateIcoPhase2 = dateIcoPhase2New; + dateIcoPhase3 = dateIcoPhase3New; + dateIcoEnd = dateIcoEndNew; + } + + //Stops an ICO. + //It will just set the ICO end date to zero and thus it will stop an ICO + function stopICO() onlyOwner public{ + dateIcoEnd = 0; + } + + //function to check wheter ICO is running or not. + //It will return current state of the crowdsale + function icoStatus() public view returns(string memory){ + if(datePreSale > now ){ + return "Pre sale has not started yet"; + } + else if(datePreSale < now && now < dateIcoPhase1){ + return "Pre sale is running"; + } + else if(dateIcoPhase1 < now && now < dateIcoPhase2){ + return "ICO phase 1 is running"; + } + else if(dateIcoPhase2 < now && now < dateIcoPhase3){ + return "ICO phase 2 is running"; + } + else if(dateIcoPhase3 < now && now < dateIcoEnd){ + return "ICO phase 3 is running"; + } + else{ + return "ICO is not active"; + } + } + + //Function to set ICO Exchange rate. + //1 ETH = How many Tokens ? + function setICOExchangeRate(uint256 newExchangeRate) onlyOwner public { + exchangeRate=newExchangeRate; + } + + //Just in case, owner wants to transfer Tokens from contract to owner address + function manualWithdrawToken(uint256 _amount) onlyOwner public { + uint256 tokenAmount = _amount.mul(1 ether); + _transfer(address(this), msg.sender, tokenAmount); + } + + //Just in case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + //selfdestruct function. just in case owner decided to destruct this contract. + function destructContract()onlyOwner public{ + selfdestruct(owner); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + /********************************/ + /* Code for the Air drop of S7N */ + /********************************/ + + /** + * Run an Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdrop(address[] memory recipients,uint tokenAmount) public onlyOwner { + uint256 addressCount = recipients.length; + require(addressCount <= 150); + for(uint i = 0; i < addressCount; i++) + { + //This will loop through all the recipients and send them the specified tokens + _transfer(address(this), recipients[i], tokenAmount.mul(1 ether)); + } + } +} diff --git a/ERC20 Tokens/Sevo Token.sol b/ERC20 Tokens/Sevo Token.sol new file mode 100644 index 0000000..c137d38 --- /dev/null +++ b/ERC20 Tokens/Sevo Token.sol @@ -0,0 +1,435 @@ +pragma solidity 0.5.16; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + ++++ + + + + + +++ + ++----++----+ +---+ +--+--++---+ +++----++ +++ ++ + ++ ++----+--+ ++ ++ +-+ +--+ ++ ++ +++ +++ +++ ++ + ++------++------+ +---+ +-----+ +-+ +-----+ +-+ +-++------++-+ +---+ + + + +=== 'SEVO' Token contract with following features === + => ERC20 Compliance + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => Burnable and minting + => User account freezing/blacklisting to prevent abusive user + => air drop (active) + + +======================= Quick Stats =================== + => Name : Sevo Token + => Symbol : SET + => Total supply: 5,000,000,000 (5 Billion) + => Decimals : 18 + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + => Community Audit by Bug Bounty program + + +------------------------------------------------------------------- + Copyright (c) 2020 onwards SEVO Coin Inc. ( https://Sevocoin.com ) + Contract designed with ? by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + + + + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + address payable internal newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + emit OwnershipTransferred(address(0), owner); + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +//****************************************************************************// +//--------------------- MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract SevoToken is owned { + + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string constant private _name = "Sevo Token"; + string constant private _symbol = "SET"; + uint256 constant private _decimals = 18; + uint256 private _totalSupply = 5000000000 * (10**_decimals); //5 billion tokens + uint256 constant public maxSupply = 5000000000 * (10**_decimals); //5 billion tokens + bool public safeguard; //putting safeguard on will halt all non-owner functions + + // This creates a mapping with all data storage + mapping (address => uint256) private _balanceOf; + mapping (address => mapping (address => uint256)) private _allowance; + mapping (address => bool) public frozenAccount; + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenAccounts(address target, bool frozen); + + // This will log approval of token Transfer + event Approval(address indexed from, address indexed spender, uint256 value); + + + + /*====================================== + = STANDARD ERC20 FUNCTIONS = + ======================================*/ + + /** + * Returns name of token + */ + function name() public pure returns(string memory){ + return _name; + } + + /** + * Returns symbol of token + */ + function symbol() public pure returns(string memory){ + return _symbol; + } + + /** + * Returns decimals of token + */ + function decimals() public pure returns(uint256){ + return _decimals; + } + + /** + * Returns totalSupply of token. + */ + function totalSupply() public view returns (uint256) { + return _totalSupply; + } + + /** + * Returns balance of token + */ + function balanceOf(address user) public view returns(uint256){ + return _balanceOf[user]; + } + + /** + * Returns allowance of token + */ + function allowance(address owner, address spender) public view returns (uint256) { + return _allowance[owner][spender]; + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguard); + require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + // overflow and undeflow checked by SafeMath Library + _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender + _balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + //checking of allowance and token value is done by SafeMath + _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + /* AUDITOR NOTE: + Many dex and dapps pre-approve large amount of tokens to save gas for subsequent transaction. This is good use case. + On flip-side, some malicious dapp, may pre-approve large amount and then drain all token balance from user. + So following condition is kept in commented. It can be be kept that way or not based on client's consent. + */ + //require(_balanceOf[msg.sender] >= _value, "Balance does not have enough tokens"); + _allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + /** + * @dev Increase the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To increment + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * Emits an Approval event. + * @param spender The address which will spend the funds. + * @param value The amount of tokens to increase the allowance by. + */ + function increase_allowance(address spender, uint256 value) public returns (bool) { + require(spender != address(0)); + _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(value); + emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); + return true; + } + + /** + * @dev Decrease the amount of tokens that an owner allowed to a spender. + * approve should be called when allowed_[_spender] == 0. To decrement + * allowed value is better to use this function to avoid 2 calls (and wait until + * the first transaction is mined) + * Emits an Approval event. + * @param spender The address which will spend the funds. + * @param value The amount of tokens to decrease the allowance by. + */ + function decrease_allowance(address spender, uint256 value) public returns (bool) { + require(spender != address(0)); + _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(value); + emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); + return true; + } + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + constructor() public{ + //sending all the tokens to Owner + _balanceOf[owner] = _totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, _totalSupply); + } + + //Fallback function just accepts incoming fund + function () external payable { + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of enough token balance is done by SafeMath + _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); // Subtract from the sender + _totalSupply = _totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenAccounts(target, freeze); + } + + /** + * @notice Create `mintedAmount` tokens and send it to `target` + * @param target Address to receive the tokens + * @param mintedAmount the amount of tokens it will receive + */ + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + require(_totalSupply.add(mintedAmount) <= maxSupply, "Cannot Mint more than maximum supply"); + _balanceOf[target] = _balanceOf[target].add(mintedAmount); + _totalSupply = _totalSupply.add(mintedAmount); + emit Transfer(address(0), target, mintedAmount); + } + + + + /** + * Owner can transfer tokens from contract to owner address + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + + /*************************************/ + /* Section for User Air drop */ + /*************************************/ + + /** + * Run an ACTIVE Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public returns(bool) { + uint256 totalAddresses = recipients.length; + require(totalAddresses <= 150,"Too many recipients"); + for(uint i = 0; i < totalAddresses; i++) + { + //This will loop through all the recipients and send them the specified tokens + //Input data validation is unncessary, as that is done by SafeMath and which also saves some gas. + transfer(recipients[i], tokenAmount[i]); + } + return true; + } + + + + + +} + diff --git a/ERC20 Tokens/South East Trading Investment Token.sol b/ERC20 Tokens/South East Trading Investment Token.sol new file mode 100644 index 0000000..e797d67 --- /dev/null +++ b/ERC20 Tokens/South East Trading Investment Token.sol @@ -0,0 +1,363 @@ +/** + *Submitted for verification at Etherscan.io on 2019-08-02 +*/ + +pragma solidity 0.5.10; /* + + + ___________________________________________________________________ + _ _ ______ + | | / / / + --|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) + __/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + ++++ + + ++ + + +----++----++--+--+ +----++---++ + ++ ++ + +----+--+ ++ + + +++++ + + +------++------+ +-+ +-+ +-----+ +-----+ +-++-+ +---+ + + + +---------------------------------------------------------------------------- + 'SETI' Token contract with following features + => ERC20 Compliance + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => Burnable and minting + => air drop + + Name : South East Trading Investment + Symbol : SETI + Total supply: 600,000,000 (600 Million) + Decimals : 18 + + +------------------------------------------------------------------------------------ + Copyright (c) 2019 onwards South East Trading Investment. All rights reserved. + Contract designed with ? by EtherAuthority ( https://EtherAuthority.io ) +----------------------------------------------------------------------------------- +*/ + + + + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/* Safemath library */ +library SafeMath { + /** + * @dev Returns the addition of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `+` operator. + * + * Requirements: + * - Addition cannot overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, "SafeMath: addition overflow"); + + return c; + } + + /** + * @dev Returns the subtraction of two unsigned integers, reverting on + * overflow (when the result is negative). + * + * Counterpart to Solidity's `-` operator. + * + * Requirements: + * - Subtraction cannot overflow. + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, "SafeMath: subtraction overflow"); + uint256 c = a - b; + + return c; + } + + /** + * @dev Returns the multiplication of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `*` operator. + * + * Requirements: + * - Multiplication cannot overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + // Gas optimization: this is cheaper than requiring 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 + if (a == 0) { + return 0; + } + + uint256 c = a * b; + require(c / a == b, "SafeMath: multiplication overflow"); + + return c; + } + + /** + * @dev Returns the integer division of two unsigned integers. Reverts on + * division by zero. The result is rounded towards zero. + * + * Counterpart to Solidity's `/` operator. Note: this function uses a + * `revert` opcode (which leaves remaining gas untouched) while Solidity + * uses an invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // Solidity only automatically asserts when dividing by 0 + require(b > 0, "SafeMath: division by zero"); + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + + return c; + } + + /** + * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), + * Reverts when dividing by zero. + * + * Counterpart to Solidity's `%` operator. This function uses a `revert` + * opcode (which leaves remaining gas untouched) while Solidity uses an + * invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + require(b != 0, "SafeMath: modulo by zero"); + return a % b; + } +} + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + + // Owner Handler + contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } + } + +//*****************************************************************// +//------------------ SETI Coin main code starts -------------------// +//*****************************************************************// + + contract SETIcoin is owned{ + // Public variables of the token + using SafeMath for uint256; + string public name = "South East Trading Investment"; + string public symbol = "SETI"; + uint256 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply = 600000000 * (10 ** decimals) ; //600 Million with 18 decimal points + bool public safeguard; //putting safeguard on will halt all non-owner functions + + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + mapping (address => bool) public frozenAccount; + + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenAccounts(address target, bool frozen); + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // Approval + event Approval(address indexed tokenOwner, address indexed spender, uint256 indexed tokenAmount); + + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor () public { + + //sending all the tokens to Owner + balanceOf[owner] = totalSupply; + + emit Transfer(address(0), msg.sender, totalSupply);// Emit event to log this transaction + + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != address(0x0)); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value && _value > 0, 'Not enough balance'); + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + + /// @notice Create `mintedAmount` tokens and send it to `target` + /// @param target Address to receive the tokens + /// @param mintedAmount the amount of tokens it will receive + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + balanceOf[target] = balanceOf[target].add(mintedAmount); + totalSupply = totalSupply.add(mintedAmount); + emit Transfer(address(0), target, mintedAmount); + } + + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenAccounts(target, freeze); + } + + + + //Just in rare case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + /********************************/ + /* Code for the Air drop */ + /********************************/ + + /** + * Run an Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdrop(address[] memory recipients, uint[] memory tokenAmount) public onlyOwner { + uint256 addressCount = recipients.length; + require(addressCount <= 150); + for(uint i = 0; i < addressCount; i++) + { + //This will loop through all the recipients and send them the specified tokens + _transfer(address(this), recipients[i], tokenAmount[i]); + } + } + + + } \ No newline at end of file diff --git a/ERC20 Tokens/Storag Coin.sol b/ERC20 Tokens/Storag Coin.sol new file mode 100644 index 0000000..f014637 --- /dev/null +++ b/ERC20 Tokens/Storag Coin.sol @@ -0,0 +1,434 @@ +pragma solidity 0.4.25; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + +███████╗████████╗ ██████╗ ██████╗ █████╗ ██████╗ ██████╗ ██████╗ ██╗███╗ ██╗ +██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗██╔══██╗██╔════╝ ██╔════╝██╔═══██╗██║████╗ ██║ +███████╗ ██║ ██║ ██║██████╔╝███████║██║ ███╗ ██║ ██║ ██║██║██╔██╗ ██║ +╚════██║ ██║ ██║ ██║██╔══██╗██╔══██║██║ ██║ ██║ ██║ ██║██║██║╚██╗██║ +███████║ ██║ ╚██████╔╝██║ ██║██║ ██║╚██████╔╝ ╚██████╗╚██████╔╝██║██║ ╚████║ +╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝╚═╝ ╚═══╝ + + + +// ---------------------------------------------------------------------------- +// 'Storag Coin' contract with following features +// => In-built ICO functionality - receive tokens when sent ether to contract address +// => ERC20 Compliance +// => Higher control of ICO by owner +// => selfdestruct functionality +// => SafeMath implementation +// => User whitelisting +// => Minting new tokens by owner +// +// Name : Storag Coin +// Symbol : STG +// Decimals : 8 +// Total supply: 1,000,000,000 (1 Billion) +// +// Copyright (c) 2018 Storag Coin Inc. The MIT Licence. +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- + +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// + /** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ + library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + } + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + + contract owned { + address public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + owner = newOwner; + } + } + + interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } + + +//***************************************************************// +//------------------ ERC20 Standard Template -------------------// +//***************************************************************// + + contract TokenERC20 { + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint256 public decimals = 8; + uint256 public totalSupply; + uint256 public reservedForICO; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor ( + uint256 initialSupply, + uint256 allocatedForICO, + string tokenName, + string tokenSymbol + ) public { + totalSupply = initialSupply.mul(1e8); // Update total supply with the decimal amount + reservedForICO = allocatedForICO.mul(1e8); // Tokens reserved For ICO + balanceOf[this] = reservedForICO; // 750 Million Tokens will remain in the contract + balanceOf[msg.sender]=totalSupply.sub(reservedForICO); // Rest of tokens will be sent to owner + name = tokenName; // Set the name for display purposes + symbol = tokenSymbol; // Set the symbol for display purposes + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != 0x0); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + + /** + * Set allowance for other address and notify + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + * @param _extraData some extra information to send to the approved contract + */ + function approveAndCall(address _spender, uint256 _value, bytes _extraData) + public + returns (bool success) { + require(!safeguard); + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, this, _extraData); + return true; + } + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + + } + +//******************************************************************************// +//--------------------- STORAG COIN MAIN CODE STARTS HERE --------------------// +//******************************************************************************// + + contract StoragCoin is owned, TokenERC20 { + + /*************************************/ + /* User whitelisting functionality */ + /*************************************/ + bool public whitelistingStatus = false; + mapping (address => bool) public whitelisted; + + /** + * Change whitelisting status on or off + * + * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. + */ + function changeWhitelistingStatus() onlyOwner public{ + if (whitelistingStatus == false){ + whitelistingStatus = true; + } + else{ + whitelistingStatus = false; + } + } + + /** + * Whitelist any user address - only Owner can do this + * + * It will add user address in whitelisted mapping + */ + function whitelistUser(address userAddress) onlyOwner public{ + require(whitelistingStatus == true); + require(userAddress != 0x0); + whitelisted[userAddress] = true; + } + + /** + * Whitelist Many user address at once - only Owner can do this + * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack + * It will add user address in whitelisted mapping + */ + function whitelistManyUsers(address[] userAddresses) onlyOwner public{ + require(whitelistingStatus == true); + uint256 addressCount = userAddresses.length; + require(addressCount <= 150); + for(uint256 i = 0; i < addressCount; i++){ + require(userAddresses[i] != 0x0); + whitelisted[userAddresses[i]] = true; + } + } + + + + /********************************/ + /* Code for the ERC20 STG Token */ + /********************************/ + + /* Public variables of the token */ + string private tokenName = "Storag Coin"; + string private tokenSymbol = "STG"; + uint256 private initialSupply = 1000000000; // 1 Billion + uint256 private allocatedForICO = 750000000; // 750 Million + + + /* Records for the fronzen accounts */ + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with initial supply tokens to the creator of the contract */ + constructor () TokenERC20(initialSupply, allocatedForICO, tokenName, tokenSymbol) public {} + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead + require (balanceOf[_from] >= _value); // Check if the sender has enough + require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + /// @notice Create `mintedAmount` tokens and send it to `target` + /// @param target Address to receive the tokens + /// @param mintedAmount the amount of tokens it will receive + function mintToken(address target, uint256 mintedAmount) onlyOwner public { + balanceOf[target] = balanceOf[target].add(mintedAmount); + totalSupply = totalSupply.add(mintedAmount); + emit Transfer(0, this, mintedAmount); + emit Transfer(this, target, mintedAmount); + } + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + + //public variables for the Crowdsale + uint256 public exchangeRate = 10000; // 1 ETH = 10000 Tokens + uint256 public tokensSold = 0; // how many tokens sold through crowdsale + + //@dev fallback function, only accepts ether if pre-sale or ICO is running or Reject + function () payable external { + require(!safeguard); + require(!frozenAccount[msg.sender]); + if(whitelistingStatus == true) { require(whitelisted[msg.sender]); } + // calculate token amount to be sent + uint256 finalTokens = msg.value.mul(exchangeRate).div(1e10); //weiamount * exchangeRate + tokensSold = tokensSold.add(finalTokens); + _transfer(this, msg.sender, finalTokens); //makes the transfers + forwardEherToOwner(); //send Ether to owner + } + + //Automatocally forwards ether from smart contract to owner address + function forwardEherToOwner() internal { + address(owner).transfer(msg.value); + } + + //Function to set ICO Exchange rate. + //1 ETH = How many Tokens ? + function setICOExchangeRate(uint256 newExchangeRate) onlyOwner public { + exchangeRate=newExchangeRate; + } + + //Just in case, owner wants to transfer Tokens from contract to owner address + function manualWithdrawToken(uint256 _amount) onlyOwner public { + uint256 tokenAmount = _amount.mul(1e8); + _transfer(this, msg.sender, tokenAmount); + } + + //Just in case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + uint256 amount=address(this).balance; + address(owner).transfer(amount); + } + + //selfdestruct function. just in case owner decided to destruct this contract. + function destructContract()onlyOwner public{ + selfdestruct(owner); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + +} diff --git a/ERC20 Tokens/Topia Shares.sol b/ERC20 Tokens/Topia Shares.sol new file mode 100644 index 0000000..07a2609 --- /dev/null +++ b/ERC20 Tokens/Topia Shares.sol @@ -0,0 +1,498 @@ +pragma solidity 0.4.25; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + +████████╗ ██████╗ ██████╗ ██╗ █████╗ ███╗ ██╗███████╗████████╗██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗ +╚══██╔══╝██╔═══██╗██╔══██╗██║██╔══██╗ ████╗ ██║██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗██║ ██╔╝ + ██║ ██║ ██║██████╔╝██║███████║ ██╔██╗ ██║█████╗ ██║ ██║ █╗ ██║██║ ██║██████╔╝█████╔╝ + ██║ ██║ ██║██╔═══╝ ██║██╔══██║ ██║╚██╗██║██╔══╝ ██║ ██║███╗██║██║ ██║██╔══██╗██╔═██╗ + ██║ ╚██████╔╝██║ ██║██║ ██║ ██║ ╚████║███████╗ ██║ ╚███╔███╔╝╚██████╔╝██║ ██║██║ ██╗ + ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ + + + +=== 'Shares' contract with following features === + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => freeze shares for dividends payments in TRX as well as TRC20 and TRC10 tokens + => unfreeze anytime.. no unfreeze cooldown time + + +======================= Quick Stats =================== + => Name : Topia Share + => Symbol : TSHARE + => Max supply : 1,000,000,000 (1 Billion) + => Decimals : 6 + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + => Community Audit by Bug Bounty program + + +------------------------------------------------------------------- + Copyright (c) 2019 onwards Topia Network Inc. ( https://topia.network ) + Contract designed with ❤ by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + + + +//**************************************************************************// +//------------------- DIVIDEND CONTRACT INTERFACE --------------------// +//**************************************************************************// + +interface InterfaceSharesDividend { + function withdrawDividendsEverything() external returns(bool); + function outstandingDivWithdrawUnFreeze() external returns(bool); +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address internal owner; + address internal newOwner; + + /** + Signer is deligated admin wallet, which can do sub-owner functions. + Signer calls following four functions: + => request fund from game contract + */ + address internal signer; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + signer = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner, 'caller must be owner'); + _; + } + + modifier onlySigner { + require(msg.sender == signer, 'caller must be signer'); + _; + } + + function changeSigner(address _signer) public onlyOwner { + signer = _signer; + } + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner, 'caller must be new owner'); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + + +//****************************************************************************// +//--------------------- SHARES MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract TopiaShares is owned { + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string public constant name = "Topia Share"; + string public constant symbol = "TSHARE"; + uint256 public constant decimals = 6; + uint256 public constant maxSupply = 1000000000 * (10**decimals); //1 Billion max supply + uint256 public totalSupply; + + address public voucherContractAddress; + address public topiaContractAddress; + address public sharesDividendContract; + bool public safeguardTokenMovement; //putting safeguard on will halt all non-owner functions + bool public globalHalt; //when this variabe will be true, then safeguardTokenMovement will be true as well. Plus it will stop minting, which also stops game contracts! + uint256 public totalMintedLifetime; + uint256 public frozenSharesGlobal; + + + // This creates a mapping with all data storage + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + mapping (address => bool) public frozenAccount; + mapping (address => uint256) public usersShareFrozen; + + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This trackes approvals + event Approval(address indexed owner, address indexed spender, uint256 value ); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenAccounts(address indexed target, bool frozen); + + + + /*====================================== + = STANDARD TRC20 FUNCTIONS = + ======================================*/ + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguardTokenMovement); + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + // overflow and undeflow checked by SafeMath Library + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + + //require(_value <= allowance[_from][msg.sender]); // no need for this condition as it is already checked by SafeMath below + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + + require(!safeguardTokenMovement); + require(balanceOf[msg.sender] >= _value, 'Not enough balance'); + + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + + return true; + } + + + + + /*===================================== + = CUSTOM SHARES FUNCTIONS = + ======================================*/ + + /** + Constructor function. nothing happens + */ + constructor() public {} + + /** + * Fallback function. It just accepts incoming TRX + */ + function () payable external {} + + + function mintShares (address user, uint256 shareMint) public returns(bool) { + + //if total supply become more than max supply, then it will just return. + //so function calling this function in voucher contract will work without minting anymore shares. + if( totalSupply > maxSupply){ return true; } + + //checking if the caller is whitelisted voucher contract + require(msg.sender==voucherContractAddress || msg.sender==owner, 'Unauthorised caller'); + + //globalHalt will affect this function, which ultimately revert the Roll functions in game contract + require(!globalHalt, 'Global Halt is on'); + + totalMintedLifetime += shareMint; + + balanceOf[user] = balanceOf[user].add(shareMint); + totalSupply = totalSupply.add(shareMint); + + //emitting Transfer event + emit Transfer(address(0),user,shareMint); + + return true; + } + + + /** + Function to freeze the shares + */ + function freezeShares(uint256 _value) public returns(bool){ + + //we want this tx.origin because user can call this directly or via any other contracts + address callingUser = tx.origin; + + //LOGIC TO WITHDRAW ANY OUTSTANDING MAIN DIVIDENDS + //we want this current call to complete if we return true from withdrawDividendsEverything, otherwise revert. + require(InterfaceSharesDividend(sharesDividendContract).withdrawDividendsEverything(), 'Outstanding div withdraw failed'); + + + //to freeze topia, we just take topia from his account and transfer to contract address, + //and track that with frozenTopia mapping variable + _transfer(callingUser, address(this), _value); + + //There is no integer underflow possibilities, as user must have that token _value, which checked in above _transfer function. + frozenSharesGlobal += _value; + usersShareFrozen[callingUser] += _value; + + + return true; + } + + function unfreezeShares() public returns(bool){ + + //we want this tx.origin because user can call this directly or via any other contracts + address callingUser = tx.origin; + + //LOGIC TO WITHDRAW ANY OUTSTANDING MAIN DIVIDENDS, ALL TOKENS AND TRX + //It will not update dividend tracker, just withdraw them. when user will freeze shares again, then automatically those trackers will be updated + require(InterfaceSharesDividend(sharesDividendContract).outstandingDivWithdrawUnFreeze(), 'Outstanding div withdraw failed'); + + + uint256 _value = usersShareFrozen[callingUser]; + + require(_value > 0 , 'Insufficient Frozen Tokens'); + + //update variables + usersShareFrozen[callingUser] = 0; + frozenSharesGlobal -= _value; + + _transfer(address(this), callingUser, _value); + + return true; + + } + + + + /*===================================== + = HELPER FUNCTIONS = + ======================================*/ + + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public returns (string) { + + frozenAccount[target] = freeze; + emit FrozenAccounts(target, freeze); + return "Wallet updated successfully"; + + } + + + function updateContractAddresses(address voucherContract, address topiaContract, address sharesDividend) public onlyOwner returns(string){ + voucherContractAddress = voucherContract; + topiaContractAddress = topiaContract; + sharesDividendContract = sharesDividend; + return "voucher, topia, share dividend conracts updated successfully"; + } + + + + /** + * Owner can transfer tokens from tonctract to owner address + */ + + function manualWithdrawShares(uint256 tokenAmount) public onlyOwner returns(string){ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + return "Tokens withdrawn to owner wallet"; + } + + + + function manualWithdrawTRC10Tokens(uint256 tokenID, uint256 tokenAmount) public onlyOwner returns(string){ + owner.transferToken(tokenAmount, tokenID); + return "Tokens withdrawn to owner wallet"; + } + + + function manualWithdrawTRX(uint256 amount) public onlyOwner returns(string){ + owner.transfer(amount); + return "TRX withdrawn to owner wallet"; + } + + + + + /** + * Change safeguardTokenMovement status on or off + * + * When safeguardTokenMovement is true, then all the non-owner functions will stop working. + * When safeguardTokenMovement is false, then all the functions will resume working back again! + */ + function changeSafeguardTokenMovement() onlyOwner public returns(string) { + if (safeguardTokenMovement == false){ + safeguardTokenMovement = true; + } + else{ + safeguardTokenMovement = false; + } + return "safeguardTokenMovement status changed"; + } + + + /** + * If global halt is off, then this funtion will on it. And vice versa + * This also change safeguard for token movement status + */ + function changeGlobalHalt() onlyOwner public returns(string) { + if (globalHalt == false){ + globalHalt = true; + safeguardTokenMovement = true; + } + else{ + globalHalt = false; + safeguardTokenMovement = false; + } + return "globalHalt status changed"; + } + + + + /** + * Function to check TRX balance in this contract + */ + function totalTRXbalanceContract() public view returns(uint256){ + return address(this).balance; + } + + + + /*********************************/ + /* Code for the Air drop */ + /*********************************/ + + /** + * Run an Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdrop(address[] recipients, uint[] tokenAmount) public onlySigner returns(string, uint256, address) { + uint256 addressCount = recipients.length; + require(addressCount == tokenAmount.length, 'both arrays must have equal length'); + for(uint i = 0; i < addressCount; i++) + { + + if (gasleft() < 100000) + { + break; + } + + //This will loop through all the recipients and send them the specified tokens + _transfer(this, recipients[i], tokenAmount[i]); + } + + return ("successful entries processed upto: ", i, recipients[i]); + } + + + + + +} \ No newline at end of file diff --git a/ERC20 Tokens/USERCoin.sol b/ERC20 Tokens/USERCoin.sol new file mode 100644 index 0000000..9afd9fe --- /dev/null +++ b/ERC20 Tokens/USERCoin.sol @@ -0,0 +1,378 @@ +pragma solidity 0.5.15; /* + + ___________________________________________________________________ + _ _ ______ + | | / / / + --|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) + __/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + ██╗ ██╗███████╗███████╗██████╗ ██████╗ ██████╗ ██╗███╗ ██╗ + ██║ ██║██╔════╝██╔════╝██╔══██╗ ██╔════╝██╔═══██╗██║████╗ ██║ + ██║ ██║███████╗█████╗ ██████╔╝ ██║ ██║ ██║██║██╔██╗ ██║ + ██║ ██║╚════██║██╔══╝ ██╔══██╗ ██║ ██║ ██║██║██║╚██╗██║ + ╚██████╔╝███████║███████╗██║ ██║ ╚██████╗╚██████╔╝██║██║ ╚████║ + ╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝╚═╝ ╚═══╝ + + + +=== 'USERCoin' Token contract with following features === + => ERC20 Compliance + => Higher degree of control by owner - safeguard functionality + => SafeMath implementation + => Burnable + => air drop (active) + => User wallet freeze function + + +======================= Quick Stats =================== + => Name : USERCoin + => Symbol : USR + => Total supply: 2,000,000,000 (2 Billion) + => Decimals : 18 + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + => Community Audit by Bug Bounty program + + +------------------------------------------------------------------- + Copyright (c) 2020 onwards USERCoin Inc. ( https://usercoin.io ) + Contract designed with ❤ by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + + + + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + address payable internal newOwner; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +//****************************************************************************// +//--------------------- MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract USERCoin is owned { + + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + string constant public name = "USERCoin"; + string constant public symbol = "USR"; + uint256 constant public decimals = 18; + uint256 public totalSupply = 2000000000 * (10**decimals); //2 billion tokens + uint256 constant public maxSupply = 2000000000 * (10**decimals); //2 billion tokens + bool public safeguard; //putting safeguard on will halt all non-owner functions + + address public burnAddress1; + address public burnAddress2; + uint256 public burnRatio1 = 50; //50 = 0.00050 % + uint256 public burnRatio2 = 25; //25 = 0.00025 % + + // This creates a mapping with all data storage + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + mapping (address => bool) public frozenAccount; + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This generates a public event for frozen (blacklisting) accounts + event FrozenAccounts(address target, bool frozen); + + // This will log approval of token Transfer + event Approval(address indexed from, address indexed spender, uint256 value); + + // This is for token swap + event TokenSwap(address indexed user, uint256 value); + + + /*====================================== + = STANDARD ERC20 FUNCTIONS = + ======================================*/ + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguard); + require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + + //burn values + uint256 burnValue1 = _value * burnRatio1 / 10000000; + uint256 burnValue2 = _value * burnRatio2 / 10000000; + uint256 receipientAmount = _value - (_value * (burnRatio1+burnRatio2) / 10000000); + + // overflow and undeflow checked by SafeMath Library + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[burnAddress1] += burnValue1; //burn to address 1 + balanceOf[burnAddress2] += burnValue2; //burn to address 2 + balanceOf[_to] += receipientAmount; // Add the remainder to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + emit Transfer(_to, burnAddress1, burnValue1); + emit Transfer(_to, burnAddress2, burnValue2); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + //checking of allowance and token value is done by SafeMath + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value, "Balance does not have enough tokens"); + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + constructor() public{ + //sending all the tokens to Owner + balanceOf[owner] = totalSupply; + + //firing event which logs this transaction + emit Transfer(address(0), owner, totalSupply); + } + + + /** + * Update Burn addresses by owner + * + * @param burnAddress1_ this is burn address 1 + * @param burnAddress2_ this is burn address 2 + */ + function updateBurnAddresses(address burnAddress1_, address burnAddress2_) public onlyOwner returns(string memory){ + burnAddress1 = burnAddress1_; + burnAddress2 = burnAddress2_; + + return "Burn addresses updated successfully"; + } + + /** + * Update Burn Percents by owner + * + * @param burnPercent1 this is burn Percents for address 1 + * @param burnPercent2 this is burn Percents for address 2 + */ + function updateBurnPercent(uint256 burnPercent1, uint256 burnPercent2) public onlyOwner returns(string memory){ + burnRatio1 = burnPercent1; + burnRatio2 = burnPercent2; + + return "Burn Percents updated successfully"; + } + + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + //checking of enough token balance is done by SafeMath + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenAccounts(target, freeze); + } + + + /** + * Owner can transfer tokens from contract to owner address + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + + function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ + // no need for overflow checking as that will be done in transfer function + _transfer(address(this), owner, tokenAmount); + } + + + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + + /*************************************/ + /* Section for User Air drop */ + /*************************************/ + /** + * Run an ACTIVE Air-Drop + * + * It requires an array of all the addresses and amount of tokens to distribute + * It will only process first 150 recipients. That limit is fixed to prevent gas limit + */ + function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public { + uint256 totalAddresses = recipients.length; + require(totalAddresses <= 150,"Too many recipients"); + for(uint64 i = 0; i < totalAddresses; i++) + { + //This will loop through all the recipients and send them the specified tokens + //Input data validation is unncessary, as that is done by SafeMath and which also saves some gas. + transfer(recipients[i], tokenAmount[i]); + } + } + + + + + + + +} \ No newline at end of file diff --git a/ERC865 Tokens/PIZ TOKEN.sol b/ERC865 Tokens/PIZ TOKEN.sol new file mode 100644 index 0000000..9a2ca0b --- /dev/null +++ b/ERC865 Tokens/PIZ TOKEN.sol @@ -0,0 +1,548 @@ +pragma solidity 0.5.2; /* + + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + +██████╗ ██╗███████╗ ████████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ +██╔══██╗██║╚══███╔╝ ╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗ ██║ +██████╔╝██║ ███╔╝ ██║ ██║ ██║█████╔╝ █████╗ ██╔██╗ ██║ +██╔═══╝ ██║ ███╔╝ ██║ ██║ ██║██╔═██╗ ██╔══╝ ██║╚██╗██║ +██║ ██║███████╗ ██║ ╚██████╔╝██║ ██╗███████╗██║ ╚████║ +╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ + + +// ---------------------------------------------------------------------------- +// 'PIZ' Token contract with following features +// => ERC20 and ERC865 Compliance +// => Higher degree of control by owner +// => selfdestruct ability by owner +// => SafeMath implementation +// => Burnable and no minting +// +// Name : PIZ TOKEN +// Symbol : PIZ +// Total supply: 8,000,000,000 (8 Billion) +// Decimals : 18 +// +// Copyright (c) 2019 PIZ TOKEN Inc. The MIT Licence. +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } +} + + + +//***************************************************************// +//------------------ ERC20 Standard Template -------------------// +//***************************************************************// + +contract TokenERC20 { + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint256 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + // This notifies client about approval of the allowance for token transfer to third party + event Approval(address indexed from, address indexed spender, uint256 value); + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor ( + uint256 initialSupply, + string memory tokenName, + string memory tokenSymbol + ) public { + totalSupply = initialSupply.mul(10**decimals); // Update total supply with the decimal amount + balanceOf[msg.sender] = totalSupply; // All the tokens will be sent to owner + name = tokenName; // Set the name for display purposes + symbol = tokenSymbol; // Set the symbol for display purposes + emit Transfer(address(0), msg.sender, totalSupply);// Emit event to log this transaction + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != address(0x0)); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + +} + +//****************************************************************************// +//--------------------- PIZ TOKEN MAIN CODE STARTS HERE ---------------------// +//****************************************************************************// + +contract PIZTOKEN is owned, TokenERC20 { + + + /***************************************/ + /* Custom Code for the ERC20 PIZ TOKEN */ + /***************************************/ + + /* Public variables of the token */ + string private tokenName = "PIZ TOKEN"; + string private tokenSymbol = "PIZ"; + uint256 private initialSupply = 8000000000; //8 Billion + + + /* Records for the fronzen accounts */ + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with initial supply tokens to the creator of the contract */ + constructor () TokenERC20(initialSupply, tokenName, tokenSymbol) public {} + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead + require (balanceOf[_from] >= _value); // Check if the sender has enough + require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + + /****************************************/ + /* Custom Code for the ERC865 PIZ TOKEN */ + /****************************************/ + + /* Nonces of transfers performed */ + mapping(bytes32 => bool) transactionHashes; + event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); + event ApprovalPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee); + + + /** + * @notice Submit a presigned transfer + * @param _to address The address which you want to transfer to. + * @param _value uint256 The amount of tokens to be transferred. + * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. + * @param _nonce uint256 Presigned transaction number. + */ + function transferPreSigned( + address _from, + address _to, + uint256 _value, + uint256 _fee, + uint256 _nonce, + uint8 v, + bytes32 r, + bytes32 s + ) + public + onlyOwner + returns (bool) + { + require(_to != address(0), 'Invalid _to address'); + bytes32 hashedTx = keccak256(abi.encodePacked('transferPreSigned', address(this), _to, _value, _fee, _nonce)); + require(transactionHashes[hashedTx] == false, 'transaction hash is already used'); + address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedTx)),v,r,s); + require(from == _from, 'Invalid _from address'); + + balanceOf[from] = balanceOf[from].sub(_value).sub(_fee); + balanceOf[_to] = balanceOf[_to].add(_value); + balanceOf[msg.sender] = balanceOf[msg.sender].add(_fee); + transactionHashes[hashedTx] = true; + emit Transfer(from, _to, _value); + emit Transfer(from, msg.sender, _fee); + emit TransferPreSigned(from, _to, msg.sender, _value, _fee); + return true; + } + + + /** + * @notice Submit a presigned approval + * @param _spender address The address which will spend the funds. + * @param _value uint256 The amount of tokens to allow. + * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. + * @param _nonce uint256 Presigned transaction number. + */ + function approvePreSigned( + address _spender, + uint256 _value, + uint256 _fee, + uint256 _nonce, + uint8 v, + bytes32 r, + bytes32 s + ) + public + onlyOwner + returns (bool) + { + require(_spender != address(0)); + bytes32 hashedTx = keccak256(abi.encodePacked('approvePreSigned', address(this), _spender, _value, _fee, _nonce)); + require(transactionHashes[hashedTx] == false, 'transaction hash is already used'); + address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedTx)),v,r,s); + require(from != address(0), 'Invalid _from address'); + allowance[from][_spender] = _value; + balanceOf[from] = balanceOf[from].sub(_fee); + balanceOf[msg.sender] = balanceOf[msg.sender].add(_fee); + transactionHashes[hashedTx] = true; + emit Approval(from, _spender, _value); + emit Transfer(from, msg.sender, _fee); + emit ApprovalPreSigned(from, _spender, msg.sender, _value, _fee); + return true; + } + + /** + * @notice Increase the amount of tokens that an owner allowed to a spender. + * @param _spender address The address which will spend the funds. + * @param _addedValue uint256 The amount of tokens to increase the allowance by. + * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. + * @param _nonce uint256 Presigned transaction number. + */ + function increaseApprovalPreSigned( + address _spender, + uint256 _addedValue, + uint256 _fee, + uint256 _nonce, + uint8 v, + bytes32 r, + bytes32 s + ) + public + onlyOwner + returns (bool) + { + require(_spender != address(0)); + bytes32 hashedTx = keccak256(abi.encodePacked('increaseApprovalPreSigned', address(this), _spender, _addedValue, _fee, _nonce)); + require(transactionHashes[hashedTx] == false, 'transaction hash is already used'); + address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedTx)),v,r,s); + require(from != address(0), 'Invalid _from address'); + allowance[from][_spender] = allowance[from][_spender].add(_addedValue); + balanceOf[from] = balanceOf[from].sub(_fee); + balanceOf[msg.sender] = balanceOf[msg.sender].add(_fee); + transactionHashes[hashedTx] = true; + emit Approval(from, _spender, allowance[from][_spender]); + emit Transfer(from, msg.sender, _fee); + emit ApprovalPreSigned(from, _spender, msg.sender, allowance[from][_spender], _fee); + return true; + } + + /** + * @notice Decrease the amount of tokens that an owner allowed to a spender. + * @param _spender address The address which will spend the funds. + * @param _subtractedValue uint256 The amount of tokens to decrease the allowance by. + * @param _fee uint256 The amount of tokens paid to msg.sender, by the owner. + * @param _nonce uint256 Presigned transaction number. + */ + function decreaseApprovalPreSigned( + address _spender, + uint256 _subtractedValue, + uint256 _fee, + uint256 _nonce, + uint8 v, + bytes32 r, + bytes32 s + ) + public + onlyOwner + returns (bool) + { + require(_spender != address(0)); + bytes32 hashedTx = keccak256(abi.encodePacked('decreaseApprovalPreSigned', address(this), _spender, _subtractedValue, _fee, _nonce)); + require(transactionHashes[hashedTx] == false, 'transaction hash is already used'); + address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedTx)),v,r,s); + require(from != address(0), 'Invalid _from address'); + if (_subtractedValue > allowance[from][_spender]) { + allowance[from][_spender] = 0; + } else { + allowance[from][_spender] = allowance[from][_spender].sub(_subtractedValue); + } + balanceOf[from] = balanceOf[from].sub(_fee); + balanceOf[msg.sender] = balanceOf[msg.sender].add(_fee); + transactionHashes[hashedTx] = true; + emit Approval(from, _spender, _subtractedValue); + emit Transfer(from, msg.sender, _fee); + emit ApprovalPreSigned(from, _spender, msg.sender, allowance[from][_spender], _fee); + return true; + } + /** + * @notice Transfer tokens from one address to another + * @param _from address The address which you want to send tokens from. + * @param _to address The address which you want to transfer to. + * @param _value uint256 The amount of tokens to be transferred. + * @param _fee uint256 The amount of tokens paid to msg.sender, by the spender. + * @param _nonce uint256 Presigned transaction number. + */ + function transferFromPreSigned( + address _from, + address _to, + uint256 _value, + uint256 _fee, + uint256 _nonce, + uint8 v, + bytes32 r, + bytes32 s + ) + public + onlyOwner + returns (bool) + { + require(_to != address(0)); + bytes32 hashedTx = keccak256(abi.encodePacked('transferFromPreSigned', address(this), _from, _to, _value, _fee, _nonce)); + require(transactionHashes[hashedTx] == false, 'transaction hash is already used'); + address spender = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedTx)),v,r,s); + require(spender != address(0), 'Invalid _from address'); + balanceOf[_from] = balanceOf[_from].sub(_value); + balanceOf[_to] = balanceOf[_to].add(_value); + allowance[_from][spender] = allowance[_from][spender].sub(_value); + balanceOf[spender] = balanceOf[spender].sub(_fee); + balanceOf[msg.sender] = balanceOf[msg.sender].add(_fee); + transactionHashes[hashedTx] = true; + emit Transfer(_from, _to, _value); + emit Transfer(spender, msg.sender, _fee); + return true; + } + + + + function testSender( + address _to, + uint256 _value, + uint256 _fee, + uint256 _nonce, + uint8 v, + bytes32 r, + bytes32 s + ) + public + view + returns (address) + { + bytes32 hashedTx = keccak256(abi.encodePacked(address(this), _to, _value, _fee, _nonce)); + return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedTx)),v,r,s); + } + + + + + + /********************************/ + /* Code for helper functions */ + /********************************/ + + //Just in case, owner wants to transfer Ether from contract to owner address + function manualWithdrawEther()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + //Just in case, owner wants to transfer Tokens from contract to owner address + //tokenAmount must be in WEI + function manualWithdrawTokens(uint256 tokenAmount)onlyOwner public{ + _transfer(address(this), msg.sender, tokenAmount); + } + + //selfdestruct function. just in case owner decided to destruct this contract. + function destructContract()onlyOwner public{ + selfdestruct(owner); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + +} diff --git a/FlashLoan/FlashLoan.sol b/FlashLoan/FlashLoan.sol new file mode 100644 index 0000000..255ed71 --- /dev/null +++ b/FlashLoan/FlashLoan.sol @@ -0,0 +1,108 @@ +//SPDX-License-Identifier: UNLICENCED +//This uses tokens of KOVAN testnet +//To get testnet tokens: https://testnet.aave.com/faucet +pragma solidity 0.6.12; + + + + +/** + * @dev Interface of the ERC20 standard as defined in the EIP. + */ +interface IERC20 { + + function approve(address spender, uint256 amount) external returns (bool); + +} + +interface IUniswapV2Router01 { + + + + function swapExactTokensForETH(uint amountIn, uint amountOutMin, 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 swapExactTokensForTokens( + uint amountIn, + uint amountOutMin, + address[] calldata path, + address to, + uint deadline + ) external returns (uint[] memory amounts); + + + +} + + +contract MyV2FlashLoan2 { + + address public LENDING_POOL = 0x9FE532197ad76c5a68961439604C037EB79681F0; + address public UniswapV2Router02 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; + address public token1 = 0xBf50BfA20D4326cB5255024B133A2EE57cdB7519; + + uint[] public test; + + receive() external payable {} + + /** + This function is called after your contract has received the flash loaned amount + */ + function executeOperation( + address[] calldata assets, + uint256[] calldata amounts, + uint256[] calldata premiums, + address initiator, + bytes calldata params + ) + external + returns (bool) + { + + // + // This contract now has the funds requested. + //first give uniswap router approval to cut tokens from this smart contract + IERC20(assets[0]).approve(UniswapV2Router02, (amounts[0] * 100)); + + + //now swap usdc to eth in uniswap + address[] memory path = new address[](2); + path[0] = assets[0]; //dai + path[1] = token1; //eat + uint[] memory amountsFromSwap1 = IUniswapV2Router01(UniswapV2Router02).swapExactTokensForTokens((amounts[0] * 5 /100), 0, path, address(this), 1111111111111111111111111); + + uint[] memory amountsFromSwap2 = IUniswapV2Router01(UniswapV2Router02).swapExactTokensForTokens((amounts[0] * 95 /100), 0, path, address(this), 1111111111111111111111111); + + + test = amountsFromSwap1; + + //give approval again to uniswap router + IERC20(token1).approve(UniswapV2Router02, (amountsFromSwap1[1] + amountsFromSwap2[1])); + + //now swap hex to usdc + address[] memory path2 = new address[](2); + path2[0] = token1; //hex + path2[1] = assets[0]; //usdc + IUniswapV2Router01(UniswapV2Router02).swapExactTokensForTokens(amountsFromSwap1[1], 0, path2, address(this), 1111111111111111111111111); + + IUniswapV2Router01(UniswapV2Router02).swapExactTokensForTokens(amountsFromSwap2[1], 0, path2, address(this), 1111111111111111111111111); + + + + + + // Approve the LendingPool contract allowance to *pull* the owed amount + for (uint i = 0; i < assets.length; i++) { + uint amountOwing = amounts[i] + premiums[i]; + IERC20(assets[i]).approve(address(LENDING_POOL), amountOwing); + } + + return true; + } +} diff --git a/Gambling/Trontopia Vault Game.sol b/Gambling/Trontopia Vault Game.sol new file mode 100644 index 0000000..9a3666a --- /dev/null +++ b/Gambling/Trontopia Vault Game.sol @@ -0,0 +1,945 @@ +pragma solidity 0.4.25; + +/* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + +████████╗██████╗ ██████╗ ███╗ ██╗ ████████╗ ██████╗ ██████╗ ██╗ █████╗ +╚══██╔══╝██╔══██╗██╔═══██╗████╗ ██║ ╚══██╔══╝██╔═══██╗██╔══██╗██║██╔══██╗ + ██║ ██████╔╝██║ ██║██╔██╗ ██║ ██║ ██║ ██║██████╔╝██║███████║ + ██║ ██╔══██╗██║ ██║██║╚██╗██║ ██║ ██║ ██║██╔═══╝ ██║██╔══██║ + ██║ ██║ ██║╚██████╔╝██║ ╚████║ ██║ ╚██████╔╝██║ ██║██║ ██║ + ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ + + + +=== 'Vault' contract with following features === + => Higher degree of control by owner - derived safeguard functionality in dependent contract + => SafeMath implementation + => Vault game logic control + + +======================= Quick Stats =================== + => Game Name : Topia Vault Game + => Based Token Name : Topia Voucher + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + => Community Audit by Bug Bounty program + + +------------------------------------------------------------------- + Copyright (c) 2019 onwards TRONtopia Inc. ( https://trontopia.co ) + Contract designed by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + /** + * @dev Returns the addition of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `+` operator. + * + * Requirements: + * - Addition cannot overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, "SafeMath: addition overflow"); + + return c; + } + + /** + * @dev Returns the subtraction of two unsigned integers, reverting on + * overflow (when the result is negative). + * + * Counterpart to Solidity's `-` operator. + * + * Requirements: + * - Subtraction cannot overflow. + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, "SafeMath: subtraction overflow"); + uint256 c = a - b; + + return c; + } + + /** + * @dev Returns the multiplication of two unsigned integers, reverting on + * overflow. + * + * Counterpart to Solidity's `*` operator. + * + * Requirements: + * - Multiplication cannot overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + // Gas optimization: this is cheaper than requiring 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 + if (a == 0) { + return 0; + } + + uint256 c = a * b; + require(c / a == b, "SafeMath: multiplication overflow"); + + return c; + } + + /** + * @dev Returns the integer division of two unsigned integers. Reverts on + * division by zero. The result is rounded towards zero. + * + * Counterpart to Solidity's `/` operator. Note: this function uses a + * `revert` opcode (which leaves remaining gas untouched) while Solidity + * uses an invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // Solidity only automatically asserts when dividing by 0 + require(b > 0, "SafeMath: division by zero"); + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + + return c; + } + + /** + * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), + * Reverts when dividing by zero. + * + * Counterpart to Solidity's `%` operator. This function uses a `revert` + * opcode (which leaves remaining gas untouched) while Solidity uses an + * invalid opcode to revert (consuming all remaining gas). + * + * Requirements: + * - The divisor cannot be zero. + */ + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + require(b != 0, "SafeMath: modulo by zero"); + return a % b; + } +} + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address public owner; + address public newOwner; + address public signer; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + signer = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + modifier onlySigner { + require(msg.sender == signer); + _; + } + + function changeSigner(address _signer) public onlyOwner { + signer = _signer; + } + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + +//**************************************************************************// +//--------------------- GAMES CONTRACT INTERFACE ---------------------// +//**************************************************************************// + +interface InterfaceGAMES { + function getAvailableVaultRake() external view returns (uint256); + function requestVaultRakePayment() external returns(bool); +} + + + +interface ERC20Essential +{ + function displayAvailableDividendALL() external returns (bool, uint256); + function distributeMainDividend() external returns(uint256); + function getDividendConfirmed(address user) external view returns (uint256); + function withdrawDividend() external returns(bool); + function balanceOf(address tokenOwner) external view returns (uint balance); + function burnVoucher(uint256 _value, uint8 mintShareStatus, address _user) external returns (bool success); + +} + + +contract vaultGame is owned +{ + + constructor () public { + + + } + + // Public variables of the token + using SafeMath for uint256; + + uint256 public minimumVoucherToBurn; // minimum amount required to burning for effective on time + uint256 public burnIncreasePerLevelInPercent = 10000; // 10000 = 100%, minimum amount will increase by percent on each deffined step + uint256 public burnIncreaseAfterStepCount=100; // after this step count reached required burning will increase by given percent + uint256 public gameClockSpanInSeconds=43200; // 43200 sec = 12 Hr. + uint256 public burnPushInSecond=30; // Will push 30 second on each burn + uint256 public secondPushDecreasePerLevel=1; // Will decrease seconds ( like lavel 1 = 30 Sec, lavel 2 = 29 Sec, lavel 3 = 28 Sec) + uint256 public gameTimer; // will keep the finished time of the game + uint256 public burnCounter; // counting of only effective burn from the start of game session + uint256 public totalVoucherBurnt; //count total effective vaucher burnt for one game session + bool public nextGameAutoStart; // if auto start is true the game will start automatically after previous end else, voucher burn by user needed to start game + mapping (address => bool) public globalToken; // The very voucher token only allowed to play here admin need to set + // This creates a mapping with all data storage + mapping (address => bool) public whitelistCaller; //Game contracts whitelisting + address[] public whitelistCallerArray; //Game contracts whitelisting + mapping (address => uint256) internal whitelistCallerArrayIndex; //Game contracts whitelisting + //uint256 public dividendAccumulated; + uint256 public divPercentageSUN = 100000000; //100% of dividend distributed + + //distribution %age can dynamically assigned by admin + uint256 toLastBurnerPercent = 2500; // 25% + uint256 toSenondLastBurnerPercent = 1500; // 15% + uint256 toThirdLastBurnerPercent = 1000; //10% + uint256 toSignerPercent = 1000; // 10% + uint256 toDividendPercent = 2500; // 25% + uint256 carryOverPercent = 1500; // 15% + mapping(address => uint256) public userTrxBalance; + uint256 public carryOverAmount; // last x % of distribution (by carryOverPercent) carrited over + + + mapping (address => uint256[]) public burnerIndicesOdd; // All records or burnerInfos index of a single user + mapping (address => uint256[]) public burnerIndicesEven; // All records or burnerInfos index of a single user + // when odd is recording burning, even will help distribution of previous dividend and vice-versa + bool public oddEven; //to help passive distribution of dividendpercent, once odd and next even will be in action + uint256 public totalVoucherBurntPrev; // burn records shifted here after session so that passive dist can work without affectins next session record + uint256 public toDividendPrev; // calculated dividend records shifted here after distribution so that passive dist can work without affectins next session record + mapping (address => uint256) public usersVaultBurnAmount; // total burn in one session by user will reset on next session + uint256 public maxBurnLimit=100000000; // User can burn only this much amount in one session + bool public globalHalt; //when this variabe will be true, then safeguardTokenMovement will be true as well. Plus it will stop minting, which also stops game contracts! + + bool biggestBurnerMode=true; // if true reward will go to biggest 3 Burner else reward will go to last three burner + address public firstHighestBurner; + address public secondHighestBurner; + address public thirdHighestBurner; + + + + // Struct to keep burning records + struct burnerInfo + { + address burner; //address of burner + uint256 burnAmount; // and his burn amount + } + + burnerInfo[] public burnerInfos; //Address of burner in series for one game session and his amount + burnerInfo[] public burnerInfosPrev; //This helps to claim dividend part for the user, once claimmed amount will be zero + mapping(address => uint256) public burnInBlock; + + //Calculate percent and return result + function calculatePercentage(uint256 PercentOf, uint256 percentTo ) internal pure returns (uint256) + { + uint256 factor = 10000; + require(percentTo <= factor); + uint256 c = PercentOf.mul(percentTo).div(factor); + return c; + } + + function () payable external {} // This contract will accept TRX , useful when distribution fetchs TRX from other contract + + function setBiggestBurnerMode(bool _biggestBurnerMode) public onlyOwner returns(bool) + { + biggestBurnerMode = _biggestBurnerMode; + } + + // To set max burn limit on one call + function setmaxBurnLimit(uint _maxBurnLimit) onlyOwner public returns(bool success) + { + maxBurnLimit = _maxBurnLimit; + return true; + } + // To set min voucher to burn on one call and its multiple will be allowed only not fractional + function setMinimumVoucherToBurn(uint _minimumVoucherToBurn) onlyOwner public returns(bool success) + { + minimumVoucherToBurn = _minimumVoucherToBurn; + return true; + } + // To set how much % amount will increase after certain steps count, if 0 will there be equal required amount for entire session + function setBurnIncreasePerLevelInPercent(uint _burnIncreasePerLevelInPercent) onlyOwner public returns(bool success) + { + burnIncreasePerLevelInPercent = _burnIncreasePerLevelInPercent; + return true; + } + // To set number of steps after which burn amount will increase by given percent + function setburnIncreaseAfterStepCount(uint _burnIncreaseAfterStepCount) onlyOwner public returns(bool success) + { + burnIncreaseAfterStepCount = _burnIncreaseAfterStepCount; + return true; + } + //To set the max duration the game will live if no burns ( default 12 Hr. ) + function setGameClockSpanInSeconds(uint _gameClockSpanInSeconds) onlyOwner public returns(bool success) + { + gameClockSpanInSeconds = _gameClockSpanInSeconds; + return true; + } + // To set if next game will start automatically (if true) or by the first burn (if false) + function setNextGameAutoStart(bool _nextGameAutoStart) onlyOwner public returns(bool success) + { + nextGameAutoStart = _nextGameAutoStart; + return true; + } + + //To set max seconds a vault can achieve when min required amount is burn, will decrease by given setting in setSecondPushDecreasePerLevel as burning count grows + function setBurnPushInSecond(uint256 _burnPushInSecond) onlyOwner public returns(bool success) + { + require(_burnPushInSecond > 1,"can not be less than 2"); + burnPushInSecond = _burnPushInSecond; + return true; + } + + // To set how much second will decrease after a certain lavel count + function setSecondPushDecreasePerLevel(uint256 _secondPushDecreasePerLevel) onlyOwner public returns(bool success) + { + secondPushDecreasePerLevel = _secondPushDecreasePerLevel; + return true; + } + // To set which voucher token will be burnt, when voucher change prev need to set false and new need to set true here + event setglobalTokenEv(uint256 nowTime, address tokenAddress, bool status); + function setglobalToken(address _globalToken, bool _enable ) onlyOwner public returns(bool success) + { + globalToken[_globalToken] = _enable; + emit setglobalTokenEv(now, _globalToken, _enable); + return true; + } + + // To set % age distribution of reward for different segment , here % is as ex 123= 1.23%, 10000 = 100% + function setDistributionPercent(uint256 _toLastBurnerPercent, uint256 _toSenondLastBurnerPercent, uint256 _toThirdLastBurnerPercent, uint256 _toSignerPercent, uint256 _toDividendPercent,uint256 _carryOverPercent) public onlyOwner returns(bool) + { + uint256 sumAll = _toLastBurnerPercent + _toSenondLastBurnerPercent + _toThirdLastBurnerPercent + _toSignerPercent + _toDividendPercent + _carryOverPercent; + require(sumAll == 10000, "sum of all is not 100%"); + toLastBurnerPercent = _toLastBurnerPercent; + toSenondLastBurnerPercent = _toSenondLastBurnerPercent; + toThirdLastBurnerPercent = _toThirdLastBurnerPercent; + toSignerPercent = _toSignerPercent; + toDividendPercent = _toDividendPercent; + carryOverPercent = _carryOverPercent; + return true; + } + // Function to burn voucher, if it is first burn then startVAultPlay will be called internally else pushMyBurn will be called + event placeMyBurnEv(address caller, uint amountBurned, uint timeNow, bool effective); + function placeMyBurn(address token, uint amountToBurn) public returns (bool) + { + require(!globalHalt, 'Global Halt is on'); + bool success; + if (gameTimer == 0) + { + success = startVaultPlay(token,amountToBurn); + } + else + { + success = pushMyBurn(token,amountToBurn); + } + emit placeMyBurnEv(msg.sender, amountToBurn,now,success); + } + + + + function startVaultPlay(address token, uint amountToBurn) internal returns(bool) + { + address starter = msg.sender; + require(amountToBurn<= maxBurnLimit,"In one call can't burn beyond limit"); + require(globalToken[token], "invalid token address"); + require(ERC20Essential(token).balanceOf(starter)>= amountToBurn,"insufficiedt balance"); + require(claimMyPart(starter),"claim for previous session failed"); + require(gameTimer == 0, "game is already on"); + require(starter != address(0), "address 0 found"); + //To check fractional amount and will revert if true means amount is not multiple of minimumVoucherToBurn + uint256 modOf = amountToBurn % minimumVoucherToBurn; + require( modOf == 0, "franctional multiple amount not valid" ); + //Burning call to voucher contract + require (ERC20Essential(token).burnVoucher(amountToBurn,2,starter),"burning failed"); + //Sum up total burning amount for user + usersVaultBurnAmount[starter] += amountToBurn; + + firstHighestBurner = starter; + + + //Increase burning counter as per given amount + uint256 countMultiple = amountToBurn / minimumVoucherToBurn; + uint i; + for (i=0;i= minimumVoucherToBurn) + { + gameTimer = now.add(gameClockSpanInSeconds); + totalVoucherBurnt = amountToBurn; + temp.burner = starter; + temp.burnAmount = amountToBurn; + burnInBlock[starter] = block.number; + if(! oddEven) + { + burnerIndicesEven[starter].push(burnerInfos.length); + } + else + { + burnerIndicesOdd[starter].push(burnerInfos.length); + } + burnerInfos.push(temp); + + success = true; + } + return success; + } + + + //To view the required amount and for how much seconds for that amount, + function whatIsRequiredNow() public view returns(uint256 reqAmount, uint256 secondAddOn) + { + //how much amount need to increase after a certain no of burn counting to calculate required amount at particular stage; + uint increaseUnitAmount = calculatePercentage(minimumVoucherToBurn,burnIncreasePerLevelInPercent); + uint increaseFactor = burnCounter.div(burnIncreaseAfterStepCount); + reqAmount = minimumVoucherToBurn.add(increaseUnitAmount.mul(increaseFactor)); + uint256 secondDecreased; + secondDecreased = secondPushDecreasePerLevel * increaseFactor; // second decreased + if(burnPushInSecond >= secondDecreased) + { + secondAddOn = burnPushInSecond - secondDecreased; + } + if (secondAddOn == 0) // if the calculated second is 0 then 1 will be return , capped on 1 + { + secondAddOn = 1; + } + return (reqAmount, secondAddOn); + } + + // If next session is set to auto start then first burn will also come to pushMyBurn, else 2nd and all next burn will call this pushMyhBurn + function pushMyBurn(address token, uint amountToBurn) internal returns(bool) + { + address callingUser = msg.sender; + require(amountToBurn<= maxBurnLimit,"In one call can't burn beyond limit"); + require(burnInBlock[callingUser] != block.number , "already burn in this block"); + burnInBlock[callingUser] = block.number; + require(globalToken[token], "invalid token address"); + require(gameTimer != 0 && gameTimer > now, "not started yet or reward distribution pending"); + require(ERC20Essential(token).balanceOf(callingUser)>= amountToBurn,"insufficiedt balance"); + require(claimMyPart(callingUser),"claim for previous session failed"); + + //how much amount need to increase after a certain no of burn counting to calculate required amount at particular stage; + uint increaseUnitAmount = calculatePercentage(minimumVoucherToBurn,burnIncreasePerLevelInPercent); + uint increaseFactor = burnCounter.div(burnIncreaseAfterStepCount); + uint requiredAmount = minimumVoucherToBurn.add(increaseUnitAmount.mul(increaseFactor)); + + // To check if amount is not in multiple of minRequiredAmount then will revert + uint256 modOf = amountToBurn % requiredAmount; // getting mod to check fraction if any in next line if freaction will revert + require( modOf == 0, "franctional multiple amount not valid" ); + //Burning called from voucher token contract + require (ERC20Essential(token).burnVoucher(amountToBurn,2,callingUser),"burning failed"); // burning voucher + usersVaultBurnAmount[callingUser] += amountToBurn; + uint256 thisAmount = usersVaultBurnAmount[callingUser]; + + if (thisAmount >= usersVaultBurnAmount[firstHighestBurner]) + { + if(callingUser != firstHighestBurner && callingUser != secondHighestBurner && callingUser != thirdHighestBurner) + { + thirdHighestBurner = secondHighestBurner; + secondHighestBurner = firstHighestBurner; + } + else if (callingUser == secondHighestBurner) + { + secondHighestBurner = firstHighestBurner; + } + else if (callingUser == thirdHighestBurner) + { + thirdHighestBurner = secondHighestBurner; + secondHighestBurner = firstHighestBurner; + } + firstHighestBurner = callingUser; + } + + if (thisAmount >= usersVaultBurnAmount[secondHighestBurner] && thisAmount < usersVaultBurnAmount[firstHighestBurner] ) + { + thirdHighestBurner = secondHighestBurner; + secondHighestBurner = callingUser; + } + + if (thisAmount >= usersVaultBurnAmount[thirdHighestBurner] && thisAmount < usersVaultBurnAmount[secondHighestBurner] ) + { + thirdHighestBurner = callingUser; + } + + + // To calculate how much second will be added for the given amount and burning counter will increase accordingly + uint256 countMultiple = amountToBurn / requiredAmount; + uint256 secondsEarned; + uint256 secondDecreased; + uint i; + for (i=0;i= burnPushInSecond) + { + secondDecreased = (burnPushInSecond -1); + } + if(burnPushInSecond > secondDecreased) + { + secondsEarned += burnPushInSecond - secondDecreased; + burnCounter ++; + increaseFactor = burnCounter.div(burnIncreaseAfterStepCount); + } + } + + //Updating burning records with the calculated seconds and its updating + burnerInfo memory temp; + + if(amountToBurn >= requiredAmount) + { + //updating calculated seconds, will never be greater than gameClockSpanInSeconds + if ((gameTimer - now + secondsEarned) <= gameClockSpanInSeconds) + { + gameTimer = gameTimer.add(secondsEarned); + } + else + { + gameTimer = gameTimer.add(gameClockSpanInSeconds - (gameTimer - now)); + } + + // Updating burning records + totalVoucherBurnt = totalVoucherBurnt.add(amountToBurn); + temp.burner = callingUser; + temp.burnAmount = amountToBurn; + if(! oddEven) + { + burnerIndicesEven[callingUser].push(burnerInfos.length); + } + else + { + burnerIndicesOdd[callingUser].push(burnerInfos.length); + } + burnerInfos.push(temp); + return true; + } + return false; + + } + + + event distributeRewardEv(uint256 toLastBurner, uint256 toSenondLastBurner, uint256 toThirdLastBurner,uint256 toSigner,uint256 toDividend,uint256 carryOverAmount ); + + // To distribute rewards will be called by admin, only then next session of vault burning will start + // If lastBurnerMode = false then reward will go to Highest Three Burner else will go to last three burner + function distributeReward() onlySigner public returns(bool) + { + //check before distribution or rewards + + require(gameTimer < now, "game not finished yet"); + //require(burnerInfos.length > 0, "no player rolled"); + + // If no burn in entire session then simply variable will reset no reward distribution else reward will be distributed + if (totalVoucherBurnt > 0) + { + //we will check dividends of all the game contract individually and sum up all values and transfering TRX to this contract + uint256 totalGameContracts = whitelistCallerArray.length; + uint256 totalDividend; + uint256 i; + for(i=0; i < totalGameContracts; i++){ + uint256 amount = InterfaceGAMES(whitelistCallerArray[i]).getAvailableVaultRake(); + if(amount > 0){ + require(InterfaceGAMES(whitelistCallerArray[i]).requestVaultRakePayment(), 'could not transfer trx'); + totalDividend += amount; + } + } + + // carryOverAmount of previous session is added in total amount + totalDividend += carryOverAmount; + + //calculating distribution parts by percentage set by admin + uint256 toLastBurner = calculatePercentage(totalDividend,toLastBurnerPercent); + uint256 toSenondLastBurner = calculatePercentage(totalDividend,toSenondLastBurnerPercent); + uint256 toThirdLastBurner = calculatePercentage(totalDividend,toThirdLastBurnerPercent); + uint256 toSigner = calculatePercentage(totalDividend,toSignerPercent); + uint256 toDividend = calculatePercentage(totalDividend,toDividendPercent); + carryOverAmount = calculatePercentage(totalDividend,carryOverPercent); + + // Distributing rewards to 1st 2nd and third Last burner + uint256 lengthOf = burnerInfos.length; + address burnerAddress; + if (! biggestBurnerMode) + { + if (lengthOf > 0 ) + { + burnerAddress = burnerInfos[lengthOf-1].burner; + userTrxBalance[burnerAddress] = userTrxBalance[burnerAddress].add(toLastBurner); + } + if (lengthOf > 1 ) + { + burnerAddress = burnerInfos[lengthOf-2].burner; + userTrxBalance[burnerAddress] = userTrxBalance[burnerAddress].add(toSenondLastBurner); + } + if (lengthOf > 2 ) + { + burnerAddress = burnerInfos[lengthOf-3].burner; + userTrxBalance[burnerAddress] = userTrxBalance[burnerAddress].add(toThirdLastBurner); + } + } + else + { + if (firstHighestBurner != address(0)) + { + userTrxBalance[firstHighestBurner] = userTrxBalance[firstHighestBurner].add(toLastBurner); + } + if (secondHighestBurner != address(0)) + { + userTrxBalance[secondHighestBurner] = userTrxBalance[secondHighestBurner].add(toSenondLastBurner); + } + if (thirdHighestBurner != address(0)) + { + userTrxBalance[thirdHighestBurner] = userTrxBalance[thirdHighestBurner].add(toThirdLastBurner); + } + } + // reward to owner + userTrxBalance[signer] = userTrxBalance[owner].add(toSigner); + + + // shifting current burning data to other variable sot the passive distribution of dividend part can work for users + // This distribution is controlled by oddEven variable once odd records current session and even distributed dividend and next vice-versa + burnerInfosPrev = burnerInfos; + totalVoucherBurntPrev = totalVoucherBurnt; + toDividendPrev = toDividend; + oddEven = ! oddEven; + } + + //Reset all data after distribution + delete burnerInfos; + burnCounter = 0; + totalVoucherBurnt = 0; + firstHighestBurner = address(0); + secondHighestBurner = address(0); + thirdHighestBurner = address(0); + + //If game is set to auto start then the reverse clock will set here else reverse clock will be 0 and will start when first burn + if(nextGameAutoStart) + { + gameTimer = now.add(gameClockSpanInSeconds); + } + else + { + gameTimer = 0; + } + emit distributeRewardEv(toLastBurner,toSenondLastBurner,toThirdLastBurner,toSigner,toDividend,carryOverAmount); + + return true; + + } + + // To give divident to specific user + //User can call this himself who want to get his part + // If admin calls need to provide user address for which award is to be claimed + function claimDivPartByOwner(address user) public onlyOwner returns(bool) + { + claimMyPart(user); + } + + // To give divident to specific user + //User can call this himself who want to get his part + // If admin calls need to provide user address for which award is to be claimed + function claimMyDivPart() public returns(bool) + { + require(!globalHalt, 'Global Halt is on'); + claimMyPart(msg.sender); + } + + event claimEv(address user,uint256 claimAmount,uint256 TotalAmountAfterClaim); + // To claim dividend this is internall called be above finction claimDivPart + function claimMyPart(address user) internal returns(bool) + { + // to all participant + address caller = user; + uint256 lengthOf; + // To check odd / even and process accordingly + // burnindices-odd/even contains all burning index of a user + // when burnerIndicesOdd records current burning burnerIndicesEven helps to claim dividends and vice-versa + if(!oddEven) + { + lengthOf = burnerIndicesOdd[caller].length; + } + else + { + lengthOf = burnerIndicesEven[caller].length; + } + + if (lengthOf == 0 ) + { + // If already distributed this function will return from here ( helpful when called this while burning in next session) + return true; + } + + // claim processed here for all burns of a specific user + // which user can withdraw later when he wants + uint256 hisPart; + uint256 amount; + + amount = usersVaultBurnAmount[caller]; + + // multiply by 1000000000 is only to avoid less tha 0 effect for un sighed integer + hisPart = (amount * toDividendPrev * 1000000000 ) / totalVoucherBurntPrev ; + hisPart = hisPart / 1000000000; + userTrxBalance[caller] = userTrxBalance[caller].add(hisPart); + //After processing records is being deleted herre + if(!oddEven) + { + delete burnerIndicesOdd[caller]; + } + else + { + delete burnerIndicesEven[caller]; + } + usersVaultBurnAmount[caller] = 0; + + emit claimEv(caller, hisPart, userTrxBalance[caller]); + return true; + } + + function viewUsersVaultBurnsThisSession(address user) public view returns(uint256) + { + uint256 lengthOf; + uint256 totalBurned; + if(!oddEven) + { + lengthOf = burnerIndicesOdd[user].length; + } + else + { + lengthOf = burnerIndicesEven[user].length; + } + if (lengthOf > 0 ) + { + totalBurned = 0 ; + } + else + { + totalBurned = usersVaultBurnAmount[user]; + } + return totalBurned; + + } + + function viewUserTrxBalance(address user) public view returns (uint256 userTotalTrx) + { + uint256 lengthOf; + if(!oddEven) + { + lengthOf = burnerIndicesOdd[user].length; + } + else + { + lengthOf = burnerIndicesEven[user].length; + } + + if (lengthOf > 0) + { + userTotalTrx = userTrxBalance[user] + (((usersVaultBurnAmount[user] * toDividendPrev * 1000000000 ) / totalVoucherBurntPrev)/1000000000) ; + } + else + { + userTotalTrx = userTrxBalance[user]; + } + return userTotalTrx; + } + + //To withdraw TRX + function withdrawTotalTrx() public returns(bool) + { + require(!globalHalt, 'Global Halt is on'); + address caller = msg.sender; + claimMyPart(caller); + uint256 totalBalance = userTrxBalance[caller]; + require(totalBalance > 0 , "nothing to withdraw"); + caller.transfer(totalBalance); + userTrxBalance[caller]=0; + return (true); + } + + // To return view of current status for UI help + function viewStat() public view returns (uint256 timeLeft, address firstLuckyBurner,uint256 firstLuckyBurnerAmount, address secondLuckyBurner,uint256 secondLuckyBurnerAmount, address thirdLuckyBurner,uint256 thirdLuckyBurnerAmount,uint256 poolSize,uint256 requiredAmountToBurn, uint256 canIncreaseSecondByBurn ) + { + if (now < gameTimer ) + { + timeLeft = gameTimer - now; + } + uint256 lengthOf = burnerInfos.length; + if( ! biggestBurnerMode ) + { + if (lengthOf > 0 ) + { + firstLuckyBurner = burnerInfos[lengthOf-1].burner; + firstLuckyBurnerAmount = burnerInfos[lengthOf-1].burnAmount; + } + if (lengthOf > 1 ) + { + secondLuckyBurner = burnerInfos[lengthOf-2].burner; + secondLuckyBurnerAmount = burnerInfos[lengthOf-2].burnAmount; + } + if (lengthOf > 2 ) + { + thirdLuckyBurner = burnerInfos[lengthOf-3].burner; + thirdLuckyBurnerAmount = burnerInfos[lengthOf-3].burnAmount; + } + } + else + { + firstLuckyBurner = firstHighestBurner; + secondLuckyBurner = secondHighestBurner; + thirdLuckyBurner = thirdHighestBurner; + firstLuckyBurnerAmount = usersVaultBurnAmount[firstHighestBurner]; + secondLuckyBurnerAmount = usersVaultBurnAmount[secondHighestBurner]; + thirdLuckyBurnerAmount = usersVaultBurnAmount[thirdHighestBurner]; + } + + poolSize = totalVoucherBurnt; + + (requiredAmountToBurn,canIncreaseSecondByBurn ) = whatIsRequiredNow(); + return (timeLeft,firstLuckyBurner,firstLuckyBurnerAmount,secondLuckyBurner,secondLuckyBurnerAmount,thirdLuckyBurner,thirdLuckyBurnerAmount,poolSize,requiredAmountToBurn,canIncreaseSecondByBurn); + } + + + + /** + This function displays all the dividend of all the game contracts + */ + // To preview the dividend + function getDividendPotential() public view returns(uint256){ + + //we will check dividends of all the game contract individually + uint256 totalGameContracts = whitelistCallerArray.length; + uint256 totalDividend; + for(uint i=0; i < totalGameContracts; i++){ + uint256 amount = InterfaceGAMES(whitelistCallerArray[i]).getAvailableVaultRake(); + if(amount > 0){ + totalDividend += amount; + } + } + + if(totalDividend > 0 ){ + + //admin can set % of dividend to be distributed. + //reason for 1000000 is that divPercentageSUN was in SUN + uint256 newAmount = totalDividend * divPercentageSUN / 100 / 1000000; + + return newAmount + carryOverAmount; + + } + else + { + return carryOverAmount; + } + + //by default it returns zero + + } + + /*===================================== + = HELPER FUNCTIONS = + ======================================*/ + + /** + * Add whitelist address who can call Mint function. Usually, they are other games contract + */ + function addWhitelistGameAddress(address _newAddress) public onlyOwner returns(string){ + + require(!whitelistCaller[_newAddress], 'No same Address again'); + + whitelistCaller[_newAddress] = true; + whitelistCallerArray.push(_newAddress); + whitelistCallerArrayIndex[_newAddress] = whitelistCallerArray.length - 1; + + return "Whitelisting Address added"; + } + + /** + * To remove any whilisted address + */ + function removeWhitelistGameAddress(address _address) public onlyOwner returns(string){ + + require(_address != address(0), 'Invalid Address'); + require(whitelistCaller[_address], 'This Address does not exist'); + + whitelistCaller[_address] = false; + uint256 arrayIndex = whitelistCallerArrayIndex[_address]; + address lastElement = whitelistCallerArray[whitelistCallerArray.length - 1]; + whitelistCallerArray[arrayIndex] = lastElement; + whitelistCallerArrayIndex[lastElement] = arrayIndex; + whitelistCallerArray.length--; + + return "Whitelisting Address removed"; + } + //Just in rare case, owner wants to transfer TRX from contract to owner address + function manualWithdrawTRX(uint256 amount) onlyOwner public returns(bool) + { + require(address(this).balance >= amount, "not enough balance to withdraw" ); + address(owner).transfer(address(this).balance); + return true; + } + + function addAmountToCarryOver(uint256 amount) public payable onlyOwner returns(bool) + { + carryOverAmount = carryOverAmount.add(amount); + } + + function changeGlobalHalt() onlySigner public returns(string) { + if (globalHalt == false){ + globalHalt = true; + } + else{ + globalHalt = false; + } + return "globalHalt status changed"; + } + +} \ No newline at end of file diff --git a/Gambling/hyperLOTTO smart contract.sol b/Gambling/hyperLOTTO smart contract.sol new file mode 100644 index 0000000..8550e12 --- /dev/null +++ b/Gambling/hyperLOTTO smart contract.sol @@ -0,0 +1,267 @@ +pragma solidity 0.5.1; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + +██╗ ██╗██╗ ██╗██████╗ ███████╗██████╗ ██╗ ██████╗ ████████╗████████╗ ██████╗ +██║ ██║╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗ ██║ ██╔═══██╗╚══██╔══╝╚══██╔══╝██╔═══██╗ +███████║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝ ██║ ██║ ██║ ██║ ██║ ██║ ██║ +██╔══██║ ╚██╔╝ ██╔═══╝ ██╔══╝ ██╔══██╗ ██║ ██║ ██║ ██║ ██║ ██║ ██║ +██║ ██║ ██║ ██║ ███████╗██║ ██║ ███████╗╚██████╔╝ ██║ ██║ ╚██████╔╝ +╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ + + + +// ---------------------------------------------------------------------------- +// 'HyperLotto' contract with following functionalities: +// => Higher control by owner +// => SafeMath implementation +// => Self destruct funcionality +// +// Contract Name : HyperLotto +// Decimals : 18 +// +// Copyright (c) 2018 HyperETH Inc. ( https://hypereth.net ) +// Contract designed by: EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- +*/ + + + +//*****************************************************************// +//---------------------- SafeMath Library -------------------------// +//*****************************************************************// + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a * b; + assert(a == 0 || c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function subsafe(uint256 a, uint256 b) internal pure returns (uint256) { + if(b <= a){ + return a - b; + }else{ + return 0; + } + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + + contract owned { + address payable public owner; + using SafeMath for uint256; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } + } + +//*******************************************************************// +//------------------ Main Contract for HyperLOTTO -------------------// +//*******************************************************************// + +contract HyperLOTTO is owned { + + /* Public variables of the smart contract */ + using SafeMath for uint256; + address[] public players; + uint256 public maxEntryAmount = 50; //50 is the maximum entries user can have in one go. For more, he can do another transaction + address public tokenContract = 0x59Ac7681e910696452b8AFf31B0c70Be6F513e81; //Token to be used in this lottery + address public lastContestent; //Person who entered in the lotto last time + uint256 public nextDrawTime = 1544484360; //Time when next draw will start, this can be changed by owner + uint256 public drawInterval = 86400; //This is seconds of draw interval, this can be changed by owner + uint256 public totalJackPotAmount; + + /* Public event that log all the winnings */ + event WinnerData(uint256 totalJackPot, address indexed mainWinner, uint256 mainWinnerAmount, address indexed lastContestent, uint256 lastContestentAmount ); + + /** + * @dev function called only by token contract, is used to enter into the contest + * @dev it will send token amount and player address + * @dev it will run for loop and add all those addresses in the array. The max is 50 now, this max amount can be changed by owner + * @dev it will also increase totalJackPotAmount and also update the lastContestent + * + * @param tokenAmount amount of tokens user sent. It will have decimals added accordingly + * @param playerAddress the address of player + * + * @return bool transaction succeed or failed + */ + function enter(uint256 tokenAmount, address playerAddress) public returns(bool) { + require(msg.sender == tokenContract, 'This function can be called only by specified token contract'); + uint256 tokenAmountFinal = tokenAmount.div(1e18); //we assume token decimal points are 18 + require(tokenAmountFinal <= maxEntryAmount, 'Token amount exceed maximum limit'); + for(uint256 i=0; i 80% to winner + * => 5% next round + * => 5% to last person to buy ticket during round + * => 10% to owner (reserve) + * @dev it will be open only when draw time has reached which is every 24 hours, + */ + function pickWinner() public onlyOwner { + require(now > nextDrawTime, 'The draw time has not come yet'); + address winner = players[random() % players.length]; + + (bool statusWinner,) = tokenContract.call(abi.encodeWithSignature("transfer(address, uint256)", winner, totalJackPotAmount*800/1000 )); + (bool statusLastPerson,) = tokenContract.call(abi.encodeWithSignature("transfer(address, uint256)", lastContestent, totalJackPotAmount*50/1000 )); + + require(statusWinner && statusLastPerson); + + emit WinnerData(totalJackPotAmount, winner, totalJackPotAmount*800/1000, lastContestent, totalJackPotAmount*50/1000 ); + + players = new address[](0); + totalJackPotAmount = totalJackPotAmount*50/1000; + nextDrawTime = nextDrawTime + drawInterval; + + } + + + function getPlayers() public view returns(address[] memory) { + // Return list of players + return players; + } + + function updateTokenContract(address _newContract) public onlyOwner{ + require(_newContract != address(0x0), 'Input address is invalid'); + tokenContract = _newContract; + } + + function updateMaxEntryAmount(uint256 _newTokenAmount) public onlyOwner{ + require(_newTokenAmount > 0, 'Input amount is invalid'); + maxEntryAmount = _newTokenAmount; + } + + //Just in case owner wants to transfer Any Ether from this contract + function manualWithdrawEther() onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + //Just in rare case, owner wants to transfer Tokens from contract to owner address + //Token amount in Wei or according to the decimal of token contract + function manualWithdrawTokens(uint tokenAmount) onlyOwner public{ + //no need to validate the input amount as transfer function automatically throws for invalid amounts + (bool status,) = tokenContract.call(abi.encodeWithSignature("transfer(address, uint256)", owner, tokenAmount )); + require(status, 'Token transfer failed'); + } + + function updateNextDrawTime(uint256 _newNextDrawTime) public onlyOwner{ + require(_newNextDrawTime > 0, 'Input amount is invalid'); + nextDrawTime = _newNextDrawTime; + } + + + //selfdestruct function. just in case owner decided to destruct this contract. + function destructContract()onlyOwner public{ + selfdestruct(owner); + } + + +} + + +contract token{ + + mapping(address => bool) public whitelistedContracts; + + function transfer(uint256 tokenAmount, address _to) public { + + if(whitelistedContracts[_to] == true){ + + (bool status,) = _to.call(abi.encodeWithSignature("enter(uint256,address)", tokenAmount, msg.sender)); + require(status, 'External contract code did not work'); + + } + + + } + + function addWhitelistedContracts(address _newContract) public{ + whitelistedContracts[_newContract] = true; + } + + function removeWhitelistedContracts(address _newContract) public{ + whitelistedContracts[_newContract] = false; + } + + +} + + + + + + + + + + + + + + + + diff --git a/Game/Double Ether (with its own token).sol b/Game/Double Ether (with its own token).sol new file mode 100644 index 0000000..89c818f --- /dev/null +++ b/Game/Double Ether (with its own token).sol @@ -0,0 +1,481 @@ +pragma solidity 0.5.1; /* + + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + +██████╗ ██████╗ ██╗ ██╗██████╗ ██╗ ███████╗ ███████╗████████╗██╗ ██╗███████╗██████╗ +██╔══██╗██╔═══██╗██║ ██║██╔══██╗██║ ██╔════╝ ██╔════╝╚══██╔══╝██║ ██║██╔════╝██╔══██╗ +██║ ██║██║ ██║██║ ██║██████╔╝██║ █████╗ █████╗ ██║ ███████║█████╗ ██████╔╝ +██║ ██║██║ ██║██║ ██║██╔══██╗██║ ██╔══╝ ██╔══╝ ██║ ██╔══██║██╔══╝ ██╔══██╗ +██████╔╝╚██████╔╝╚██████╔╝██████╔╝███████╗███████╗ ███████╗ ██║ ██║ ██║███████╗██║ ██║ +╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ + + +// ---------------------------------------------------------------------------- +// 'Double Ether' Token contract with following features +// => ERC20 Compliance +// => Safeguard functionality - Higher degree of control by owner +// => selfdestruct ability by owner +// => SafeMath implementation +// => Burnable and no minting +// +// Name : Double Ether +// Symbol : DET +// Total supply: 100,000,000 (100 Million) +// Decimals : 18 +// +// Copyright (c) 2018 Deteth Inc. ( https://deteth.com ) +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- + +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// + /** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ + library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + } + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + + contract owned { + address payable public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } + } + + interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } + + +//***************************************************************// +//------------------ ERC20 Standard Template -------------------// +//***************************************************************// + + contract TokenERC20 { + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it + uint256 public totalSupply; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor ( + uint256 initialSupply, + string memory tokenName, + string memory tokenSymbol + ) public { + + totalSupply = initialSupply * 1 ether; // Update total supply with the decimal amount + uint256 halfTotalSupply = totalSupply / 2; // Half of the totalSupply + + balanceOf[msg.sender] = halfTotalSupply; // 50 Million tokens sent to owner + balanceOf[address(this)] = halfTotalSupply; // 50 Million tokens sent to smart contract + name = tokenName; // Set the name for display purposes + symbol = tokenSymbol; // Set the symbol for display purposes + + emit Transfer(address(0x0), msg.sender, halfTotalSupply); // Transfer event + emit Transfer(address(0x0), address(this), halfTotalSupply);// Transfer event + } + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != address(0x0)); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + + /** + * Set allowance for other address and notify + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + * @param _extraData some extra information to send to the approved contract + */ + function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) + public + returns (bool success) { + require(!safeguard); + tokenRecipient spender = tokenRecipient(_spender); + if (approve(_spender, _value)) { + spender.receiveApproval(msg.sender, _value, address(this), _extraData); + return true; + } + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + + } + +//*******************************************************************************// +//--------------------- DOUBLE ETHER MAIN CODE STARTS HERE ---------------------// +//*******************************************************************************// + + contract DoubleEther is owned, TokenERC20 { + + + /********************************/ + /* Code for the ERC20 DET Token */ + /********************************/ + + /* Public variables of the token */ + string internal tokenName = "Double Ether"; + string internal tokenSymbol = "DET"; + uint256 internal initialSupply = 100000000; //100 Million + + + /* Records for the fronzen accounts */ + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with initial supply tokens to the creator of the contract */ + constructor () TokenERC20(initialSupply, tokenName, tokenSymbol) public {} + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead + require (balanceOf[_from] >= _value); // Check if the sender has enough + require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + + /*******************************************/ + /* Code for the Double Ether Functionality */ + /*******************************************/ + + + uint256 public returnPercentage = 150; // 150% return, which is 1.5 times the amount deposited + uint256 public additionalFund = 0; + address payable[] public winnerQueueAddresses; + uint256[] public winnerQueueAmount; + + // This will log for all the deposits made by users + event Deposit(address indexed depositor, uint256 depositAmount); + + // This will log for any ether paid to users + event RewardPaid(address indexed rewardPayee, uint256 rewardAmount); + + function showPeopleInQueue() public view returns(uint256) { + return winnerQueueAmount.length; + } + + //@dev fallback function, which accepts ether + function () payable external { + require(!safeguard); + require(!frozenAccount[msg.sender]); + require(msg.value >= 0.5 ether); + + //If users send more than 3 ether, then it will consider only 3 ether, and rest goes to owner as service fee + uint256 _depositedEther; + if(msg.value >= 3 ether){ + _depositedEther = 3 ether; + additionalFund += msg.value - 3 ether; + } + else{ + _depositedEther = msg.value; + } + + + //following loop will send reward to one or more addresses + uint256 TotalPeopleInQueue = winnerQueueAmount.length; + for(uint256 index = 0; index < TotalPeopleInQueue; index++){ + + if(winnerQueueAmount[0] <= (address(this).balance - additionalFund) ){ + + //transfer the ether and token to leader / first position + winnerQueueAddresses[0].transfer(winnerQueueAmount[0]); + _transfer(address(this), winnerQueueAddresses[0], winnerQueueAmount[0]*100/returnPercentage); + + //this will shift one index up in both arrays, removing the person who is paid + for (uint256 i = 0; i 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address public owner; + address internal newOwner; + + /** + Signer is deligated admin wallet, which can do sub-owner functions. + Signer calls following function: + => withdraw + */ + address public signer; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + signer = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + modifier onlySigner { + require(msg.sender == signer); + _; + } + + function changeSigner(address _signer) public onlyOwner { + signer = _signer; + } + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + +contract HXXD is owned{ + using SafeMath for uint256; + string constant public name = "HXXD"; + string constant public symbol = "HXXD"; + uint256 constant public decimals = 8; + uint256 constant internal tronDecimals = 6; + uint256 public totalSupply = 10000000 * (10 ** decimals); + bool public safeguard = false; + + // This creates a mapping with all data storage + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + mapping (address => bool) public frozenAccount; + + //event + event Withdraw(address indexed user,uint amount,uint256 timestamp); + event Deposit(address indexed user,uint amount,uint256 timestamp); + // This generates a public event of token transfer + event Transfer(address indexed from, address indexed to, uint256 value); + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + // This will log approval of token Transfer + event Approval(address indexed from, address indexed spender, uint256 value); + + + + /*====================================== + = STANDARD TRC20 FUNCTIONS = + ======================================*/ + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + + //checking conditions + require(!safeguard); + require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead + + // overflow and undeflow checked by SafeMath Library + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + + // emit Transfer event + emit Transfer(_from, _to, _value); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + //no need to check for input validations, as that is ruled by SafeMath + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + emit Approval(msg.sender, _spender, _value); + return true; + } + + + + /*===================================== + = CUSTOM PUBLIC FUNCTIONS = + ======================================*/ + + /** + * Fallback function. It just accepts incoming TRX + */ + function () payable external {} + + /** + constroctor function to send all the tokens to owner + */ + constructor() public{ + //sending all the tokens to Owner + balanceOf[owner] = totalSupply; + //firing event which logs this transaction + emit Transfer(address(0), owner, totalSupply); + } + + /** + Deposit of TRX function. + */ + function deposit() public payable returns(bool){ + require(!safeguard); + emit Deposit(msg.sender,msg.value,now); + return true; + } + + /** + This allows owner to send trx to users + */ + function withdraw(address user,uint256 amount) public onlySigner returns(bool){ + require(!safeguard); + require(amount > 0,'Amount should be greater then 0'); + require(user != address(0), 'Invalid Address'); + user.transfer(amount); + emit Withdraw(user,amount,now); + return true; + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + emit Transfer(msg.sender, address(0), _value); + return true; + } + + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public returns(string){ + if (safeguard == false){ + safeguard = true; + return "Sageguard Activated Successfully"; + } + else{ + safeguard = false; + return "Safeguard Removed Successfully"; + } + } + + +} \ No newline at end of file diff --git a/Game/Place It - Pixel Game.sol b/Game/Place It - Pixel Game.sol new file mode 100644 index 0000000..5e22dcb --- /dev/null +++ b/Game/Place It - Pixel Game.sol @@ -0,0 +1,763 @@ +pragma solidity 0.4.25; /* + + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + +██████╗ ██╗ █████╗ ██████╗███████╗ ██╗████████╗ +██╔══██╗██║ ██╔══██╗██╔════╝██╔════╝ ██║╚══██╔══╝ +██████╔╝██║ ███████║██║ █████╗ ██║ ██║ +██╔═══╝ ██║ ██╔══██║██║ ██╔══╝ ██║ ██║ +██║ ███████╗██║ ██║╚██████╗███████╗ ██║ ██║ +╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝ ╚═╝ ╚═╝ + + +// ---------------------------------------------------------------------------- +// 'PlaceIt' Token contract with following features +// => PlaceIt - Game complete functionality +// => TR20 Compliance +// => Higher degree of control by owner +// => selfdestruct ability by owner +// => SafeMath implementation +// => Burnable and no minting +// +// Name : PlaceIt +// Symbol : PLACE +// Total supply: 1,000,000,000 (1 Billion) +// Decimals : 8 +// +// Copyright (c) 2019 PlaceIt Inc. ( https://PlaceIt.io ) +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// ---------------------------------------------------------------------------- + +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + owner = newOwner; + } +} + + + +//*************************************************************// +//------------------ TR20 Standard Template -------------------// +//*************************************************************// + +contract TokenTR20 { + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint256 public decimals = 8; + uint256 public totalSupply; + bool public safeguard = false; //putting safeguard on will halt all non-owner functions + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt + event Burn(address indexed from, uint256 value); + + /** + * Constrctor function + * + * Initializes contract with initial supply tokens to the creator of the contract + */ + constructor ( + uint256 initialSupply, + string memory tokenName, + string memory tokenSymbol + ) public { + totalSupply = initialSupply.mul(10**decimals); // Update total supply with the decimal amount + balanceOf[msg.sender] = totalSupply; // All the tokens will be sent to owner + name = tokenName; // Set the name for display purposes + symbol = tokenSymbol; // Set the symbol for display purposes + + emit Transfer(address(0), msg.sender, totalSupply); + } + + /** + * fallback function. It just accepts any incoming fund into smart contract + */ + function () payable external { } + + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != address(0x0)); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + + /** + * Destroy tokens + * + * Remove `_value` tokens from the system irreversibly + * + * @param _value the amount of money to burn + */ + function burn(uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[msg.sender] >= _value); // Check if the sender has enough + balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender + totalSupply = totalSupply.sub(_value); // Updates totalSupply + emit Burn(msg.sender, _value); + return true; + } + + /** + * Destroy tokens from other account + * + * Remove `_value` tokens from the system irreversibly on behalf of `_from`. + * + * @param _from the address of the sender + * @param _value the amount of money to burn + */ + function burnFrom(address _from, uint256 _value) public returns (bool success) { + require(!safeguard); + require(balanceOf[_from] >= _value); // Check if the targeted balance is enough + require(_value <= allowance[_from][msg.sender]); // Check allowance + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance + totalSupply = totalSupply.sub(_value); // Update totalSupply + emit Burn(_from, _value); + return true; + } + +} + +//**************************************************************************// +//--------------------- PLACEIT MAIN CODE STARTS HERE ---------------------// +//**************************************************************************// + +contract PlaceIt is owned, TokenTR20 { + + + /*********************************/ + /* Code for the TR20 PLACE Token */ + /*********************************/ + + /* Public variables of the token */ + string private tokenName = "PlaceIt"; //Name of the token + string private tokenSymbol = "PLACE"; //Symbol of the token + uint256 private initialSupply = 1000000000; //1 Billion + uint256 public sellPrice = 10; //Price to sell tokens to smart contract + uint256 public buyPrice = 10; //Price to buy tokens from smart contract + + + /* Records for the fronzen accounts */ + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with initial supply tokens to the creator of the contract */ + constructor () TokenTR20(initialSupply, tokenName, tokenSymbol) public {} + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead + require (balanceOf[_from] >= _value); // Check if the sender has enough + require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + /** + * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + * @param target Address to be frozen + * @param freeze either to freeze it or not + */ + function freezeAccount(address target, bool freeze) onlyOwner public { + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + /** + * @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth + * @param newSellPrice Price the users can sell to the contract + * @param newBuyPrice Price users can buy from the contract + */ + function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { + sellPrice = newSellPrice; + buyPrice = newBuyPrice; + } + + /** + * @notice Buy tokens from contract by sending ether + */ + function buyTokens() payable public { + uint256 amount = msg.value.mul(buyPrice).div(1e10); // calculates the amount + _transfer(address(this), msg.sender, amount); // makes the transfers + } + + /** + * @notice Sell `amount` tokens to contract + * @param amount amount of tokens to be sold. It must be in 8 decimals + */ + function sellTokens(uint256 amount) public { + address myAddress = address(this); + uint256 tronAmount = amount.mul(1e10).div(sellPrice); + require(myAddress.balance >= tronAmount); // checks if the contract has enough ether to buy + _transfer(msg.sender, address(this), amount); // makes the transfers + msg.sender.transfer(tronAmount); // sends ether to the seller. It's important to do this last to avoid recursion attacks + } + + /*********************************/ + /* Code for Main PlaceIt Game */ + /*********************************/ + + //--- Public variables of the PlaceIt -------------// + uint256 public pixelPrice = 10 * (10**decimals); //10 TRX for 1 pixel + uint256 public communityPoolVolume = 0; //Total TRX accumulated for commuinty pool for any given round + uint256 public minimumTokenRequirement = 500 * (10**decimals); //User must have at least 500 Tokens to be eligible to receive winnings + uint256 public poolMinimumRequirement = 7000000 * (10**decimals); //7 Million + uint256 public communityMinimumPixel = 100; //Community must have this many pixel purchased to be eligible for winning + uint256 public createCommunityFee = 1000 * (10**decimals); //1000 TRX to create a community + uint256 public joinCommunityFee = 100 * (10**decimals); //100 TRX to join a community + uint256 public leaveCommunityFee = 1 * (10**decimals); //1 TRX to leave a community + address public foundersAddress = TH2se4Ccx5LbGeLMYGqkDVQbNoDPo3E8zF; + address public developersAddress = TQ9KeSAi8PXvPWVYyTaVF9jdp65FTBACyf; + address public maintainanceAddress = TGGnB81bATA6he2ZEVeFzXU2yzmi5YZ49m; + address public charityAddress = TBBnsH1UJMMyjAKWQj3cKtfSmQzsDK78aN; + + + //--- Data storage variables -----------------------// + mapping(bytes32=>bool) public allCommunities; //Mapping holds whether community exist + mapping(bytes32=>address[]) communityTotalUsers;//Mapping holds total users for each community + mapping(address=>uint) indexOfCommunityUsers; //Mapping holds index of particular user in communityTotalUsers array + mapping(bytes32=>uint256) communityTotalPixels; //Mapping holds purchase volume for each community + mapping(address=>uint256) public userTotalPixels; //Mapping to hold all the addresses and their total pixels + mapping(address=>bytes32) public usertoCommunity; //Mapping to hold all the addresses and their communities + mapping(bytes32=>address) pixelDimensionToUsers; //Mapping for pixes dimension to users + mapping(bytes32=>address) pixelColorToUsers; //Mapping for pixes color to users + bytes32[] public communitiesArray; //Array of all the communities + address[] public userTotalPixelsTemp; //Temporary Array which holds all the users who purchased pixels + bytes32[] internal pixelDimensionToUsersTemp; //Temporary Array which holds all the pixels dimension purchased + + + //--- Public Events to log activities in GUI -----------// + event CommunityCreated(bytes32 communityName, address indexed communityCreator, uint256 timestamp); + event CommunityJoined(bytes32 communityName, address indexed member, uint256 timestamp); + event CommunityLeft(bytes32 communityName, address indexed member, uint256 timestamp); + event PixelPurchased(address indexed byer, bytes32[] pixelPositionArray, bytes32[] colorArray, uint256 timestamp); + event PickWinnerData(bytes32 winnerCommunity, uint256 communityPoolVolume, uint256 communityTotalPixels, uint256 communityTotalUsers, uint256 timestamp ); + + + /** + * @notice Whilte creating community user must pay 1000 TRX. + * @notice The name of community must be unique. Obviously users can not use the same name of any existing community. + * + * @param communityName The name of new community. + */ + + function createNewCommunicty(bytes32 communityName) payable public { + + require(msg.value == createCommunityFee, 'Payment Amount is not valid'); + require(!allCommunities[communityName], 'Community name is already taken. Please use unique name'); + + allCommunities[communityName] = true; + communitiesArray.push(communityName); + + emit CommunityCreated(communityName, msg.sender, now); + } + + + /** + * @notice User joins a new community. + * @notice It requires the community exist, and then it also requires the user does not present in any other communities. + * + * @param communityName The name of the community user wish to join. + * + * @return bool true if all good. + */ + function joinCommunity(bytes32 communityName) public payable returns(bool) { + + require(msg.value == joinCommunityFee, 'Payment Amount is not valid'); + require(allCommunities[communityName], 'Community does not exist'); + require(usertoCommunity[msg.sender] == bytes32(0), 'Member belongs to other community. He must first leave that community before joining new one'); + + usertoCommunity[msg.sender] = communityName; + communityTotalUsers[communityName].push(msg.sender); + indexOfCommunityUsers[msg.sender] = communityTotalUsers[communityName].length - 1; + + emit CommunityJoined(communityName, msg.sender, now); + + return true; + + } + + /** + * @notice Function allows user to leave community. + * @notice User must exist in any community. + * + * @return bool Return true if all good. + */ + function leaveCommunity() payable public returns(bool) { + + require(msg.value == leaveCommunityFee, 'Payment Amount is not valid'); + require(usertoCommunity[msg.sender] != bytes32(0), 'User is not present in any community'); + + uint index = indexOfCommunityUsers[msg.sender]; + address [] memory addressArray = communityTotalUsers[usertoCommunity[msg.sender]]; + addressArray[index] = addressArray[addressArray.length-1]; + communityTotalUsers[usertoCommunity[msg.sender]].length--; // Implicitly recovers gas from last element storage + + emit CommunityLeft(usertoCommunity[msg.sender], msg.sender, now); + + usertoCommunity[msg.sender] = ""; + + return true; + } + + + /** + * @notice Function to buy pixel. + * @notice It has unrestrictive loop. But since it cost lots of fund to run DoS attack, it is impossible to do any harm. + * @notice And for any genuine users, it will be fine as Tron has high gas limits. + * + * @param pixelPositionArray An array of bytes32 of all the pixel dimension. + * + * @return bool It returns true if all good. + */ + function buyPixels(bytes32[] memory pixelPositionArray, bytes32[] memory colorArray) payable public returns(bool){ + + require(pixelPositionArray.length > 0, 'Buyer must purchase at least one position'); + require(pixelPositionArray.length == colorArray.length, 'Dimension and Color array are not the same'); + require(msg.value >= pixelPositionArray.length * pixelPrice, 'User has provided insufficient fund'); + require(usertoCommunity[msg.sender] != bytes32(0), 'User does not belong to any community.'); + require(allCommunities[usertoCommunity[msg.sender]], 'Community does not exist'); + + for(uint i=0; i= poolMinimumRequirement, 'Pool minimum volume is not enough'); + bytes32 winnerCommunity = checkWinnerCommunity(); + require(winnerCommunity != bytes32(0), 'No winnerCommunity selected'); + + //70% winning to individual members according to their contribution + uint256 availablePoolAmount = communityPoolVolume * 700 / 1000; + for(uint i=0; i= minimumTokenRequirement){ + uint256 winingAmountPercent = userTotalPixels[user] * 100 / availablePoolAmount; + uint256 winningAmount = availablePoolAmount * winingAmountPercent / 100; + //transfering winning amount to user + user.transfer(winningAmount); + } + } + + //12% goes to cost and maintainance + maintainanceAddress.transfer(communityPoolVolume * 120 / 1000); + //8% goes to founders + foundersAddress.transfer(communityPoolVolume * 80 / 1000); + //7% goes to developers + developersAddress.transfer(communityPoolVolume * 70 / 1000); + //3% goest to charity + charityAddress.transfer(communityPoolVolume * 30 / 1000); + + + //Logging winner data in event + emit PickWinnerData(winnerCommunity, communityPoolVolume, communityTotalPixels[winnerCommunity], communityTotalUsers[winnerCommunity].length, now); + + + //clearning everything to begin fresh for next round + communityPoolVolume = 0; + //clearing communityTotalPixels Mapping + for(uint a=0; a largest && totalPixels >= communityMinimumPixel) { + largest = totalPixels; + winnerCommunity = communitiesArray[i]; + } + } + if(largest>0){ + return winnerCommunity; + }else{ + return bytes32(0); + } + } + + + + //**********************************************// + //----- Functions to Visualise information -----// + //**********************************************// + + /** + * @notice check if community exist. + * @param communityName the name of community to look for. + * @return bool Returns true or false. + */ + function viewCommunityExist(bytes32 communityName) public view returns(bool){ + return allCommunities[communityName]; + } + + + /** + * @notice It returns total number of communities. + * @notice It is used to display the total community dropdown in GUI. + * @notice This number is the total loop iteration has to be done to look into communitiesArray. + * @return uint256 Total number of communities. + */ + function viewTotalCommunities() public view returns(bytes32[] memory){ + return communitiesArray; + } + + + /** + * @notice View total number of users exist in any community. + * @param communityName the name of community to look for. + * @return bool Returns no of user exist in given community. + */ + function viewTotalUsersInCommunity(bytes32 communityName) public view returns(uint256){ + return communityTotalUsers[communityName].length; + } + + + /** + * @notice View how many pixels purchased in any community. + * @param communityName the name of community to look for. + * @return bool Returns no of pixels purchased in given community. + */ + function viewTotalPixelsInCommunity(bytes32 communityName) public view returns(uint256){ + return communityTotalPixels[communityName]; + } + + + /** + * @notice View the buyer who purchased a particular pixel dimension. + * @param pixelDimension the name of pixel Dimension bytes32 to look for. + * @return address Returns address of buyer who purchased particular pixel. + */ + function viewPixelOwner(bytes32 pixelDimension) public view returns(address){ + return pixelDimensionToUsers[pixelDimension]; + } + + + + //*************************************************// + //-------- Code for the Helper functions ----------// + //*************************************************// + + /** + * @notice Update pixelPrice. + * @param pixelPrice_ Amount of fee to purchase one pixel. + * @return bool true for success transaction. + */ + function updatePixelPrice (uint256 pixelPrice_) public onlyOwner returns(bool){ + require(pixelPrice_ > 0, 'Invalid amount'); + pixelPrice = pixelPrice_ * (10**decimals); + return true; + } + + /** + * @notice Update createCommunityFee. + * @param createCommunityFee_ Amount of fee to create community. + * @return bool true for success transaction. + */ + function updateCreateCommunityFee (uint256 createCommunityFee_) public onlyOwner returns(bool){ + require(createCommunityFee_ > 0, 'Invalid amount'); + createCommunityFee = createCommunityFee_ * (10**decimals); + return true; + } + + /** + * @notice Update joinCommunityFee. + * @param joinCommunityFee_ Amount of fee to join community. + * @return bool true for success transaction. + */ + function updateJoinCommunityFee (uint256 joinCommunityFee_) public onlyOwner returns(bool){ + require(joinCommunityFee_ > 0, 'Invalid amount'); + joinCommunityFee = joinCommunityFee_ * (10**decimals); + return true; + } + + /** + * @notice Update leaveCommunityFee. + * @param leaveCommunityFee_ Amount of fee to leave community. + * @return bool true for success transaction. + */ + function updateLeaveCommunityFee (uint256 leaveCommunityFee_) public onlyOwner returns(bool){ + require(leaveCommunityFee_ > 0, 'Invalid amount'); + leaveCommunityFee = leaveCommunityFee_ * (10**decimals); + return true; + } + + /** + * @notice Update poolMinimumRequirement. + * @param poolMinimumRequirement_ Minimum fund accumulated in pool to execute winner selection. + * @return bool true for success transaction. + */ + function updatePoolMinimumRequirement (uint256 poolMinimumRequirement_) public onlyOwner returns(bool){ + require(poolMinimumRequirement_ > 0, 'Invalid amount'); + poolMinimumRequirement = poolMinimumRequirement_ * (10**decimals); + return true; + } + + /** + * @notice Update minimumTokenRequirement. + * @param minimumTokenRequirement_ Minimum tokens user must have to be eligible to receive winning. + * @return bool true for success transaction. + */ + function updateMinimumTokenRequirement (uint256 minimumTokenRequirement_) public onlyOwner returns(bool){ + require(minimumTokenRequirement_ > 0, 'Invalid amount'); + minimumTokenRequirement = minimumTokenRequirement_ * (10**decimals); + return true; + } + + /** + * @notice Update communityMinimumPixel. + * @param communityMinimumPixel_ Minimum pixels must be purchased in comminity to be eligible to receive winning. + * @return bool true for success transaction. + */ + function updateCommunityMinimumPixel (uint256 communityMinimumPixel_) public onlyOwner returns(bool){ + require(communityMinimumPixel_ > 0, 'Invalid amount'); + communityMinimumPixel = communityMinimumPixel_ ; + return true; + } + + + /** + * @notice Update Founders Address. It must be called by owner only. + * @param _newFounderAddress New address of founder. + * @return bool true for success transaction. + */ + function updateFoundersAddress(address _newFounderAddress) public onlyOwner returns(bool){ + require(_newFounderAddress != address(0), 'Invalid address'); + foundersAddress = _newFounderAddress; + return true; + } + + /** + * @notice Update Developer Address. It must be called by owner only. + * @param developersAddress_ New address of Developer. + * @return bool true for success transaction. + */ + function updateDevelopersAddress(address developersAddress_) public onlyOwner returns(bool){ + require(developersAddress_ != address(0), 'Invalid address'); + developersAddress = developersAddress_; + return true; + } + + /** + * @notice Update Maintainance Address. It must be called by owner only. + * @param maintainanceAddress_ New address for maintainance. + * @return bool true for success transaction. + */ + function updateMaintainanceAddress(address maintainanceAddress_) public onlyOwner returns(bool){ + require(maintainanceAddress_ != address(0), 'Invalid address'); + maintainanceAddress = maintainanceAddress_; + return true; + } + + /** + * @notice Update Charity Address. It must be called by owner only. + * @param charityAddress_ New address for charity. + * @return bool true for success transaction. + */ + function updateCharityAddress(address charityAddress_) public onlyOwner returns(bool){ + require(charityAddress_ != address(0), 'Invalid address'); + charityAddress = charityAddress_; + return true; + } + + /** + * @notice Just in case, owner wants to transfer Tron from contract to owner address + */ + function manualWithdrawTron()onlyOwner public{ + address(owner).transfer(address(this).balance); + } + + /** + * @notice selfdestruct function. just in case owner decided to destruct this contract. + */ + function destructContract()onlyOwner public{ + selfdestruct(owner); + } + + /** + * @notice Change safeguard status on or off + * @notice When safeguard is true, then all the non-owner functions will stop working. + * @notice When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + + + +} diff --git a/NFT - Non Fungible Tokens/Niftymoji.sol b/NFT - Non Fungible Tokens/Niftymoji.sol new file mode 100644 index 0000000..f13fba8 --- /dev/null +++ b/NFT - Non Fungible Tokens/Niftymoji.sol @@ -0,0 +1,1320 @@ +/** + *Submitted for verification at Etherscan.io on 2020-02-25 +*/ + +pragma solidity ^0.5.16; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + +███╗ ██╗██╗███████╗████████╗██╗ ██╗ ███╗ ███╗ ██████╗ ██╗██╗ +████╗ ██║██║██╔════╝╚══██╔══╝╚██╗ ██╔╝ ████╗ ████║██╔═══██╗ ██║██║ +██╔██╗ ██║██║█████╗ ██║ ╚████╔╝ ██╔████╔██║██║ ██║ ██║██║ +██║╚██╗██║██║██╔══╝ ██║ ╚██╔╝ ██║╚██╔╝██║██║ ██║██ ██║██║ +██║ ╚████║██║██║ ██║ ██║ ██║ ╚═╝ ██║╚██████╔╝╚█████╔╝██║ +╚═╝ ╚═══╝╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚════╝ ╚═╝ + + +=== 'Niftymoji' NFT Management contract with following features === + => ERC721 Compliance + => ERC165 Compliance + => SafeMath implementation + => Generation of new digital assets + => Destroyal of digital assets + + +============= Independant Audit of the code ============ + => Multiple Freelancers Auditors + + +------------------------------------------------------------------- + Copyright (c) 2019 onwards Niftymoji Inc. ( https://niftymoji.com ) +------------------------------------------------------------------- +*/ + + +/** + * @title Ownable + * @dev The Ownable contract has an owner address, and provides basic authorization control + * functions, this simplifies the implementation of "user permissions". + */ +contract Ownable { + address payable internal _owner; + + event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); + + /** + * @dev The Ownable constructor sets the original `owner` of the contract to the sender + * account. + */ + constructor () internal { + _owner = msg.sender; + emit OwnershipTransferred(address(0), _owner); + } + + /** + * @return the address of the owner. + */ + function owner() public view returns (address) { + return _owner; + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyOwner() { + require(isOwner()); + _; + } + + /** + * @return true if `msg.sender` is the owner of the contract. + */ + function isOwner() public view returns (bool) { + return msg.sender == _owner; + } + + /** + * @dev Allows the current owner to relinquish control of the contract. + * It will not be possible to call the functions with the `onlyOwner` + * modifier anymore. + * @notice Renouncing ownership will leave the contract without an owner, + * thereby removing any functionality that is only available to the owner. + */ + function renounceOwnership() public onlyOwner { + emit OwnershipTransferred(_owner, address(0)); + _owner = address(0); + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferOwnership(address payable newOwner) public onlyOwner { + _transferOwnership(newOwner); + } + + /** + * @dev Transfers control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function _transferOwnership(address payable newOwner) internal { + require(newOwner != address(0)); + emit OwnershipTransferred(_owner, newOwner); + _owner = newOwner; + } +} + + +// File: contracts/Strings.sol + +pragma solidity ^0.5.2; + +library Strings { + // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol + function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { + bytes memory _ba = bytes(_a); + bytes memory _bb = bytes(_b); + bytes memory _bc = bytes(_c); + bytes memory _bd = bytes(_d); + bytes memory _be = bytes(_e); + string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); + bytes memory babcde = bytes(abcde); + uint k = 0; + for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; + for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; + for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; + for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; + for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; + return string(babcde); + } + + function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { + return strConcat(_a, _b, _c, _d, ""); + } + + function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { + return strConcat(_a, _b, _c, "", ""); + } + + function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { + return strConcat(_a, _b, "", "", ""); + } + + function uint2str(uint _i) internal pure returns (string memory _uintAsString) { + if (_i == 0) { + return "0"; + } + uint j = _i; + uint len; + while (j != 0) { + len++; + j /= 10; + } + bytes memory bstr = new bytes(len); + uint k = len - 1; + while (_i != 0) { + bstr[k--] = byte(uint8(48 + _i % 10)); + _i /= 10; + } + return string(bstr); + } + + function fromAddress(address addr) internal pure returns(string memory) { + bytes20 addrBytes = bytes20(addr); + bytes16 hexAlphabet = "0123456789abcdef"; + bytes memory result = new bytes(42); + result[0] = '0'; + result[1] = 'x'; + for (uint i = 0; i < 20; i++) { + result[i * 2 + 2] = hexAlphabet[uint8(addrBytes[i] >> 4)]; + result[i * 2 + 3] = hexAlphabet[uint8(addrBytes[i] & 0x0f)]; + } + return string(result); + } +} + +// File: openzeppelin-solidity/contracts/introspection/IERC165.sol + +pragma solidity ^0.5.2; + +/** + * @title IERC165 + * @dev https://eips.ethereum.org/EIPS/eip-165 + */ +interface IERC165 { + /** + * @notice Query if a contract implements an interface + * @param interfaceId The interface identifier, as specified in ERC-165 + * @dev Interface identification is specified in ERC-165. This function + * uses less than 30,000 gas. + */ + function supportsInterface(bytes4 interfaceId) external view returns (bool); +} + +// File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol + +pragma solidity ^0.5.2; + + +/** + * @title ERC721 Non-Fungible Token Standard basic interface + * @dev see https://eips.ethereum.org/EIPS/eip-721 + */ +contract IERC721 is IERC165 { + event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); + event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); + event ApprovalForAll(address indexed owner, address indexed operator, bool approved); + + function balanceOf(address owner) public view returns (uint256 balance); + function ownerOf(uint256 tokenId) public view returns (address owner); + + function approve(address to, uint256 tokenId) public; + function getApproved(uint256 tokenId) public view returns (address operator); + + function setApprovalForAll(address operator, bool _approved) public; + function isApprovedForAll(address owner, address operator) public view returns (bool); + + function transferFrom(address from, address to, uint256 tokenId) public; + function safeTransferFrom(address from, address to, uint256 tokenId) public; + + function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; +} + +// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol + +pragma solidity ^0.5.2; + +/** + * @title ERC721 token receiver interface + * @dev Interface for any contract that wants to support safeTransfers + * from ERC721 asset contracts. + */ +contract IERC721Receiver { + /** + * @notice Handle the receipt of an NFT + * @dev The ERC721 smart contract calls this function on the recipient + * after a `safeTransfer`. This function MUST return the function selector, + * otherwise the caller will revert the transaction. The selector to be + * returned can be obtained as `this.onERC721Received.selector`. This + * function MAY throw to revert and reject the transfer. + * Note: the ERC721 contract address is always the message sender. + * @param operator The address which called `safeTransferFrom` function + * @param from The address which previously owned the token + * @param tokenId The NFT identifier which is being transferred + * @param data Additional data with no specified format + * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` + */ + function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) + public returns (bytes4); +} + +// File: openzeppelin-solidity/contracts/math/SafeMath.sol + +pragma solidity ^0.5.2; + +/** + * @title SafeMath + * @dev Unsigned math operations with safety checks that revert on error + */ +library SafeMath { + /** + * @dev Multiplies two unsigned integers, reverts on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + // Gas optimization: this is cheaper than requiring 'a' not being zero, but the + // benefit is lost if 'b' is also tested. + // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 + if (a == 0) { + return 0; + } + + uint256 c = a * b; + require(c / a == b); + + return c; + } + + /** + * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // Solidity only automatically asserts when dividing by 0 + require(b > 0); + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + + return c; + } + + /** + * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a); + uint256 c = a - b; + + return c; + } + + /** + * @dev Adds two unsigned integers, reverts on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a); + + return c; + } + + /** + * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), + * reverts when dividing by zero. + */ + function mod(uint256 a, uint256 b) internal pure returns (uint256) { + require(b != 0); + return a % b; + } +} + +// File: openzeppelin-solidity/contracts/utils/Address.sol + +pragma solidity ^0.5.2; + +/** + * Utility library of inline functions on addresses + */ +library Address { + /** + * Returns whether the target address is a contract + * @dev This function will return false if invoked during the constructor of a contract, + * as the code is not actually created until after the constructor finishes. + * @param account address of the account to check + * @return whether the target address is a contract + */ + function isContract(address account) internal view returns (bool) { + uint256 size; + // XXX Currently there is no better way to check if there is a contract in an address + // than to check the size of the code at that address. + // See https://ethereum.stackexchange.com/a/14016/36603 + // for more details about how this works. + // TODO Check this again before the Serenity release, because all addresses will be + // contracts then. + // solhint-disable-next-line no-inline-assembly + assembly { size := extcodesize(account) } + return size > 0; + } +} + +// File: openzeppelin-solidity/contracts/drafts/Counters.sol + +pragma solidity ^0.5.2; + + +/** + * @title Counters + * @author Matt Condon (@shrugs) + * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number + * of elements in a mapping, issuing ERC721 ids, or counting request ids + * + * Include with `using Counters for Counters.Counter;` + * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath + * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never + * directly accessed. + */ +library Counters { + using SafeMath for uint256; + + struct Counter { + // This variable should never be directly accessed by users of the library: interactions must be restricted to + // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add + // this feature: see https://github.com/ethereum/solidity/issues/4637 + uint256 _value; // default: 0 + } + + function current(Counter storage counter) internal view returns (uint256) { + return counter._value; + } + + function increment(Counter storage counter) internal { + counter._value += 1; + } + + function decrement(Counter storage counter) internal { + counter._value = counter._value.sub(1); + } +} + +// File: openzeppelin-solidity/contracts/introspection/ERC165.sol + +pragma solidity ^0.5.2; + + +/** + * @title ERC165 + * @author Matt Condon (@shrugs) + * @dev Implements ERC165 using a lookup table. + */ +contract ERC165 is IERC165 { + bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; + /* + * 0x01ffc9a7 === + * bytes4(keccak256('supportsInterface(bytes4)')) + */ + + /** + * @dev a mapping of interface id to whether or not it's supported + */ + mapping(bytes4 => bool) private _supportedInterfaces; + + /** + * @dev A contract implementing SupportsInterfaceWithLookup + * implement ERC165 itself + */ + constructor () internal { + _registerInterface(_INTERFACE_ID_ERC165); + } + + /** + * @dev implement supportsInterface(bytes4) using a lookup table + */ + function supportsInterface(bytes4 interfaceId) external view returns (bool) { + return _supportedInterfaces[interfaceId]; + } + + /** + * @dev internal method for registering an interface + */ + function _registerInterface(bytes4 interfaceId) internal { + require(interfaceId != 0xffffffff); + _supportedInterfaces[interfaceId] = true; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol + +pragma solidity ^0.5.2; + + + + +interface OldNiftymoji{ + function powerNLucks(uint256 tokenID) external returns(uint256, uint256); +} + + + + +/** + * @title ERC721 Non-Fungible Token Standard basic implementation + * @dev see https://eips.ethereum.org/EIPS/eip-721 + */ +contract ERC721 is ERC165, IERC721 { + using SafeMath for uint256; + using Address for address; + using Counters for Counters.Counter; + + struct powerNLuck + { + uint256 power; + uint256 luck; + } + + uint256 public totalSupply; + + //uint256 is tokenNo and powerNLuck is associated details in uint256 + mapping (uint256 => powerNLuck) public powerNLucks; + + // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` + // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` + bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; + + // Mapping from token ID to owner + mapping (uint256 => address) private _tokenOwner; + + // Mapping from token ID to approved address + mapping (uint256 => address) private _tokenApprovals; + + // Mapping from owner to number of owned token + mapping (address => Counters.Counter) private _ownedTokensCount; + + // Mapping from owner to operator approvals + mapping (address => mapping (address => bool)) private _operatorApprovals; + + bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; + /* + * 0x80ac58cd === + * bytes4(keccak256('balanceOf(address)')) ^ + * bytes4(keccak256('ownerOf(uint256)')) ^ + * bytes4(keccak256('approve(address,uint256)')) ^ + * bytes4(keccak256('getApproved(uint256)')) ^ + * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ + * bytes4(keccak256('isApprovedForAll(address,address)')) ^ + * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ + * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ + * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) + */ + + constructor () public { + // register the supported interfaces to conform to ERC721 via ERC165 + _registerInterface(_INTERFACE_ID_ERC721); + } + + /** + * @dev Gets the balance of the specified address + * @param owner address to query the balance of + * @return uint256 representing the amount owned by the passed address + */ + function balanceOf(address owner) public view returns (uint256) { + require(owner != address(0)); + return _ownedTokensCount[owner].current(); + } + + /** + * @dev Gets the owner of the specified token ID + * @param tokenId uint256 ID of the token to query the owner of + * @return address currently marked as the owner of the given token ID + */ + function ownerOf(uint256 tokenId) public view returns (address) { + address owner = _tokenOwner[tokenId]; + require(owner != address(0)); + return owner; + } + + /** + * @dev Approves another address to transfer the given token ID + * The zero address indicates there is no approved address. + * There can only be one approved address per token at a given time. + * Can only be called by the token owner or an approved operator. + * @param to address to be approved for the given token ID + * @param tokenId uint256 ID of the token to be approved + */ + function approve(address to, uint256 tokenId) public { + address owner = ownerOf(tokenId); + require(to != owner); + require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); + + _tokenApprovals[tokenId] = to; + emit Approval(owner, to, tokenId); + } + + /** + * @dev Gets the approved address for a token ID, or zero if no address set + * Reverts if the token ID does not exist. + * @param tokenId uint256 ID of the token to query the approval of + * @return address currently approved for the given token ID + */ + function getApproved(uint256 tokenId) public view returns (address) { + require(_exists(tokenId)); + return _tokenApprovals[tokenId]; + } + + /** + * @dev Sets or unsets the approval of a given operator + * An operator is allowed to transfer all tokens of the sender on their behalf + * @param to operator address to set the approval + * @param approved representing the status of the approval to be set + */ + function setApprovalForAll(address to, bool approved) public { + require(to != msg.sender); + _operatorApprovals[msg.sender][to] = approved; + emit ApprovalForAll(msg.sender, to, approved); + } + + /** + * @dev Tells whether an operator is approved by a given owner + * @param owner owner address which you want to query the approval of + * @param operator operator address which you want to query the approval of + * @return bool whether the given operator is approved by the given owner + */ + function isApprovedForAll(address owner, address operator) public view returns (bool) { + return _operatorApprovals[owner][operator]; + } + + /** + * @dev Transfers the ownership of a given token ID to another address + * Usage of this method is discouraged, use `safeTransferFrom` whenever possible + * Requires the msg.sender to be the owner, approved, or operator + * @param from current owner of the token + * @param to address to receive the ownership of the given token ID + * @param tokenId uint256 ID of the token to be transferred + */ + function transferFrom(address from, address to, uint256 tokenId) public { + require(_isApprovedOrOwner(msg.sender, tokenId)); + + _transferFrom(from, to, tokenId); + } + + /** + * @dev Safely transfers the ownership of a given token ID to another address + * If the target address is a contract, it must implement `onERC721Received`, + * which is called upon a safe transfer, and return the magic value + * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, + * the transfer is reverted. + * Requires the msg.sender to be the owner, approved, or operator + * @param from current owner of the token + * @param to address to receive the ownership of the given token ID + * @param tokenId uint256 ID of the token to be transferred + */ + function safeTransferFrom(address from, address to, uint256 tokenId) public { + safeTransferFrom(from, to, tokenId, ""); + } + + /** + * @dev Safely transfers the ownership of a given token ID to another address + * If the target address is a contract, it must implement `onERC721Received`, + * which is called upon a safe transfer, and return the magic value + * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, + * the transfer is reverted. + * Requires the msg.sender to be the owner, approved, or operator + * @param from current owner of the token + * @param to address to receive the ownership of the given token ID + * @param tokenId uint256 ID of the token to be transferred + * @param _data bytes data to send along with a safe transfer check + */ + function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { + transferFrom(from, to, tokenId); + require(_checkOnERC721Received(from, to, tokenId, _data)); + } + + /** + * @dev Returns whether the specified token exists + * @param tokenId uint256 ID of the token to query the existence of + * @return bool whether the token exists + */ + function _exists(uint256 tokenId) internal view returns (bool) { + address owner = _tokenOwner[tokenId]; + return owner != address(0); + } + + /** + * @dev Returns whether the given spender can transfer a given token ID + * @param spender address of the spender to query + * @param tokenId uint256 ID of the token to be transferred + * @return bool whether the msg.sender is approved for the given token ID, + * is an operator of the owner, or is the owner of the token + */ + function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { + address owner = ownerOf(tokenId); + return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); + } + + /** + * @dev Internal function to mint a new token + * Reverts if the given token ID already exists + * @param to The address that will own the minted token + * @param tokenId uint256 ID of the token to be minted + */ + function _mint(address to, uint256 tokenId, uint256 _userSeed) internal { + require(to != address(0)); + require(!_exists(tokenId)); + require(totalSupply <= 3187, 'Excedend Max Token Supply'); + + _tokenOwner[tokenId] = to; + _ownedTokensCount[to].increment(); + totalSupply++; + + //generating random numbers for luck and power based on previous blockhash and user seed + //this method of entropy is not very secure, but kept it as consent of client + uint256 _luck = uint256(keccak256(abi.encodePacked(blockhash( block.number -1), _userSeed))) % 100; //0-99 + uint256 _power = uint256(keccak256(abi.encodePacked(blockhash( block.number -10), now, _userSeed))) % 100; //0-99 + //assigning lucky no and power to tokenId + powerNLucks[tokenId].luck = _luck+1; //this will cause it will never be zero. + powerNLucks[tokenId].power = _power+1; //this will cause it will never be zero. + + emit Transfer(address(0), to, tokenId); + } + + function _mintSyncedTokens(uint256 tokenID, address user) internal { + + _tokenOwner[tokenID] = user; + _ownedTokensCount[user].increment(); + totalSupply++; + + //generating random numbers for luck and power based on previous blockhash and user seed + //this method of entropy is not very secure, but kept it as consent of client + (uint256 _power, uint256 _luck) = OldNiftymoji(0x40b16A1b6bEA856745FeDf7E0946494B895611a2).powerNLucks(tokenID); //mainnet + //(uint256 _power, uint256 _luck) = OldNiftymoji(0x03f701FB8EA5441A9Bf98B65461e795931B55298).powerNLucks(tokenID); //testnet + + //assigning lucky no and power to tokenId + powerNLucks[tokenID].luck = _luck; //this will cause it will never be zero. + powerNLucks[tokenID].power = _power; //this will cause it will never be zero. + + emit Transfer(address(0), user, tokenID); + } + + + + /** + * @dev Internal function to burn a specific token + * Reverts if the token does not exist + * Deprecated, use _burn(uint256) instead. + * @param owner owner of the token to burn + * @param tokenId uint256 ID of the token being burned + */ + function _burn(address owner, uint256 tokenId) internal { + require(ownerOf(tokenId) == owner); + + _clearApproval(tokenId); + + _ownedTokensCount[owner].decrement(); + _tokenOwner[tokenId] = address(0); + + emit Transfer(owner, address(0), tokenId); + } + + /** + * @dev Internal function to burn a specific token + * Reverts if the token does not exist + * @param tokenId uint256 ID of the token being burned + */ + function _burn(uint256 tokenId) internal { + _burn(ownerOf(tokenId), tokenId); + } + + /** + * @dev Internal function to transfer ownership of a given token ID to another address. + * As opposed to transferFrom, this imposes no restrictions on msg.sender. + * @param from current owner of the token + * @param to address to receive the ownership of the given token ID + * @param tokenId uint256 ID of the token to be transferred + */ + function _transferFrom(address from, address to, uint256 tokenId) internal { + require(ownerOf(tokenId) == from); + require(to != address(0)); + + _clearApproval(tokenId); + + _ownedTokensCount[from].decrement(); + _ownedTokensCount[to].increment(); + + _tokenOwner[tokenId] = to; + + emit Transfer(from, to, tokenId); + } + + /** + * @dev Internal function to invoke `onERC721Received` on a target address + * The call is not executed if the target address is not a contract + * @param from address representing the previous owner of the given token ID + * @param to target address that will receive the tokens + * @param tokenId uint256 ID of the token to be transferred + * @param _data bytes optional data to send along with the call + * @return bool whether the call correctly returned the expected magic value + */ + function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) + internal returns (bool) + { + if (!to.isContract()) { + return true; + } + + bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); + return (retval == _ERC721_RECEIVED); + } + + /** + * @dev Private function to clear current approval of a given token ID + * @param tokenId uint256 ID of the token to be transferred + */ + function _clearApproval(uint256 tokenId) private { + if (_tokenApprovals[tokenId] != address(0)) { + _tokenApprovals[tokenId] = address(0); + } + } + + + +} + +// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Enumerable.sol + +pragma solidity ^0.5.2; + + +/** + * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension + * @dev See https://eips.ethereum.org/EIPS/eip-721 + */ +contract IERC721Enumerable is IERC721 { + //function totalSupply() public view returns (uint256); + function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); + + function tokenByIndex(uint256 index) public view returns (uint256); +} + +// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Enumerable.sol + +pragma solidity ^0.5.2; + + + + +/** + * @title ERC-721 Non-Fungible Token with optional enumeration extension logic + * @dev See https://eips.ethereum.org/EIPS/eip-721 + */ +contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { + // Mapping from owner to list of owned token IDs + mapping(address => uint256[]) private _ownedTokens; + + // Mapping from token ID to index of the owner tokens list + mapping(uint256 => uint256) private _ownedTokensIndex; + + // Array with all token ids, used for enumeration + uint256[] private _allTokens; + + // Mapping from token id to position in the allTokens array + mapping(uint256 => uint256) private _allTokensIndex; + + bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; + /* + * 0x780e9d63 === + * bytes4(keccak256('totalSupply()')) ^ + * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ + * bytes4(keccak256('tokenByIndex(uint256)')) + */ + + /** + * @dev Constructor function + */ + constructor () public { + // register the supported interface to conform to ERC721Enumerable via ERC165 + _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); + } + + /** + * @dev Gets the token ID at a given index of the tokens list of the requested owner + * @param owner address owning the tokens list to be accessed + * @param index uint256 representing the index to be accessed of the requested tokens list + * @return uint256 token ID at the given index of the tokens list owned by the requested address + */ + function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { + require(index < balanceOf(owner)); + return _ownedTokens[owner][index]; + } + + /** + * @dev Gets the total amount of tokens stored by the contract + * @return uint256 representing the total amount of tokens + */ + function totalSupplyEnum() public view returns (uint256) { + return _allTokens.length; + } + + /** + * @dev Gets the token ID at a given index of all the tokens in this contract + * Reverts if the index is greater or equal to the total number of tokens + * @param index uint256 representing the index to be accessed of the tokens list + * @return uint256 token ID at the given index of the tokens list + */ + function tokenByIndex(uint256 index) public view returns (uint256) { + require(index < totalSupplyEnum()); + return _allTokens[index]; + } + + + + /** + * @dev Gets the list of token IDs of the requested owner + * @param owner address owning the tokens + * @return uint256[] List of token IDs owned by the requested address + */ + function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { + return _ownedTokens[owner]; + } + + /** + * @dev Private function to add a token to this extension's ownership-tracking data structures. + * @param to address representing the new owner of the given token ID + * @param tokenId uint256 ID of the token to be added to the tokens list of the given address + */ + function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { + _ownedTokensIndex[tokenId] = _ownedTokens[to].length; + _ownedTokens[to].push(tokenId); + } + + /** + * @dev Private function to add a token to this extension's token tracking data structures. + * @param tokenId uint256 ID of the token to be added to the tokens list + */ + function _addTokenToAllTokensEnumeration(uint256 tokenId) private { + _allTokensIndex[tokenId] = _allTokens.length; + _allTokens.push(tokenId); + } + + /** + * @dev Internal function to mint a new token + * Reverts if the given token ID already exists + * @param to address the beneficiary that will own the minted token + * @param tokenId uint256 ID of the token to be minted + */ + function _mint(address to, uint256 tokenId) internal { + super._mint(to, tokenId,0); + + _addTokenToOwnerEnumeration(to, tokenId); + + _addTokenToAllTokensEnumeration(tokenId); + } + + /** + * @dev Internal function to burn a specific token + * Reverts if the token does not exist + * Deprecated, use _burn(uint256) instead + * @param owner owner of the token to burn + * @param tokenId uint256 ID of the token being burned + */ + function _burn(address owner, uint256 tokenId) internal { + super._burn(owner, tokenId); + + _removeTokenFromOwnerEnumeration(owner, tokenId); + // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund + _ownedTokensIndex[tokenId] = 0; + + _removeTokenFromAllTokensEnumeration(tokenId); + } + + /** + * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that + * while the token is not assigned a new owner, the _ownedTokensIndex mapping is _not_ updated: this allows for + * gas optimizations e.g. when performing a transfer operation (avoiding double writes). + * This has O(1) time complexity, but alters the order of the _ownedTokens array. + * @param from address representing the previous owner of the given token ID + * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address + */ + function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { + // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and + // then delete the last slot (swap and pop). + + uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); + uint256 tokenIndex = _ownedTokensIndex[tokenId]; + + // When the token to delete is the last token, the swap operation is unnecessary + if (tokenIndex != lastTokenIndex) { + uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; + + _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token + _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index + } + + // This also deletes the contents at the last position of the array + _ownedTokens[from].length--; + + // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by + // lastTokenId, or just over the end of the array if the token was the last one). + } + + /** + * @dev Private function to remove a token from this extension's token tracking data structures. + * This has O(1) time complexity, but alters the order of the _allTokens array. + * @param tokenId uint256 ID of the token to be removed from the tokens list + */ + function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { + // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and + // then delete the last slot (swap and pop). + + uint256 lastTokenIndex = _allTokens.length.sub(1); + uint256 tokenIndex = _allTokensIndex[tokenId]; + + // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so + // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding + // an 'if' statement (like in _removeTokenFromOwnerEnumeration) + uint256 lastTokenId = _allTokens[lastTokenIndex]; + + _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token + _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index + + // This also deletes the contents at the last position of the array + _allTokens.length--; + _allTokensIndex[tokenId] = 0; + } +} + +// File: openzeppelin-solidity/contracts/token/ERC721/IERC721Metadata.sol + +pragma solidity ^0.5.2; + + +/** + * @title ERC-721 Non-Fungible Token Standard, optional metadata extension + * @dev See https://eips.ethereum.org/EIPS/eip-721 + */ +contract IERC721Metadata is IERC721 { + function name() external view returns (string memory); + function symbol() external view returns (string memory); + function tokenURI(uint256 tokenId) external view returns (string memory); +} + +// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol + +pragma solidity ^0.5.2; + + + + +contract ERC721Metadata is ERC165, IERC721Metadata, ERC721 { + // Token name + string private _name; + + // Token symbol + string private _symbol; + + // Optional mapping for token URIs + mapping(uint256 => string) private _tokenURIs; + + bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; + /* + * 0x5b5e139f === + * bytes4(keccak256('name()')) ^ + * bytes4(keccak256('symbol()')) ^ + * bytes4(keccak256('tokenURI(uint256)')) + */ + + /** + * @dev Constructor function + */ + constructor (string memory name, string memory symbol) public { + _name = name; + _symbol = symbol; + + // register the supported interfaces to conform to ERC721 via ERC165 + _registerInterface(_INTERFACE_ID_ERC721_METADATA); + } + + /** + * @dev Gets the token name + * @return string representing the token name + */ + function name() external view returns (string memory) { + return _name; + } + + /** + * @dev Gets the token symbol + * @return string representing the token symbol + */ + function symbol() external view returns (string memory) { + return _symbol; + } + + /** + * @dev Returns an URI for a given token ID + * Throws if the token ID does not exist. May return an empty string. + * @param tokenId uint256 ID of the token to query + */ + function tokenURI(uint256 tokenId) external view returns (string memory) { + require(_exists(tokenId)); + return _tokenURIs[tokenId]; + } + + /** + * @dev Internal function to set the token URI for a given token + * Reverts if the token ID does not exist + * @param tokenId uint256 ID of the token to set its URI + * @param uri string URI to assign + */ + function _setTokenURI(uint256 tokenId, string memory uri) internal { + require(_exists(tokenId)); + _tokenURIs[tokenId] = uri; + } + + /** + * @dev Internal function to burn a specific token + * Reverts if the token does not exist + * Deprecated, use _burn(uint256) instead + * @param owner owner of the token to burn + * @param tokenId uint256 ID of the token being burned by the msg.sender + */ + function _burn(address owner, uint256 tokenId) internal { + super._burn(owner, tokenId); + + // Clear metadata (if any) + if (bytes(_tokenURIs[tokenId]).length != 0) { + delete _tokenURIs[tokenId]; + } + } +} + +// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol + +pragma solidity ^0.5.2; + + + + +/** + * @title Full ERC721 Token + * This implementation includes all the required and some optional functionality of the ERC721 standard + * Moreover, it includes approve all functionality using operator terminology + * @dev see https://eips.ethereum.org/EIPS/eip-721 + */ +contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { + constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { + // solhint-disable-previous-line no-empty-blocks + } +} + + +// File: contracts/TradeableERC721Token.sol + +pragma solidity ^0.5.2; + + + + +contract OwnableDelegateProxy { } + + + +contract ProxyRegistry { + mapping(address => OwnableDelegateProxy) public proxies; +} + +/** + * @title TradeableERC721Token + * TradeableERC721Token - ERC721 contract that whitelists a trading address, and has minting functionality. + */ +contract TradeableERC721Token is ERC721Full, Ownable { + using Strings for string; + + uint256 public tokenPrice=5 * (10**16) ; //price of token to buy + address proxyRegistryAddress; + uint256 private _currentTokenId = 0; + + + + constructor(string memory _name, string memory _symbol) ERC721Full(_name, _symbol) public { + } + + /** + * @dev Mints a token to an address with a tokenURI. + * @param _to address of the future owner of the token + */ + function mintTo(address _to) public onlyOwner { + uint256 newTokenId = _getNextTokenId(); + _mint(_to, newTokenId,0); + _incrementTokenId(); + } + + + function setTokenPrice(uint256 _tokenPrice) public onlyOwner returns(bool) + { + tokenPrice = _tokenPrice; + return true; + } + + + function buyToken(uint256 _userSeed) public payable returns(bool) + { + uint256 paidAmount = msg.value; + require(paidAmount == tokenPrice, "Invalid amount paid"); + uint256 newTokenId = _getNextTokenId(); + _mint(msg.sender, newTokenId,_userSeed); + _incrementTokenId(); + _owner.transfer(paidAmount); + return true; + } + + function batchMintToken(address[] memory _buyer) public onlyOwner returns(bool) + { + uint256 buyerLength = _buyer.length; + require(buyerLength <= 100, "please try less then 101"); + for(uint256 i=0;i B will get the money from the escrow. + + +MAIN COMPONENTS +=> Ownership of contract +=> Oracle system +=> Main Fish Trade +=> Escrow system + + + +POSSIBLE EVENTS: +If the fish is not of good quality: A has to report to B that the fish is not of good quality. +If A reports that the fish is not of good quality in 2 hours, A will get his money back from the escrow. +If the fish is not delivered in time, that means not on the 1st of February 2019: +If the fish does not get delivered to A in time, that means not on the 1st of February 2019, A will get his money back from the escrow. + +If A doesn’t accept the delivery: If A does not accept the right delivery, +(The delivery is right when: - The delivery of 5kg fish - In Good Quality - On the 1st of February 2019. - At A’s place. ) +B still gets the money from the escrow. + +The data about fish is coming from the Oracle, which handled by the Oracle Contract + + +*/ + + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + + contract owned { + address public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + owner = newOwner; + } + } + +//*******************************************************************// +//--------------------- Contract for Oracle -------------------------// +//*******************************************************************// + + contract Oracle is owned { + + /* Public variables of Oracle */ + bool fishQuality; + uint256 fishQuantity; + uint256 deliveryDate; + + /* Struct which holds all the requests received by the oracle for the logging purpose */ + struct Request { + bool fishQuality; + uint256 fishQuantity; + uint256 deliveryDate; + } + + /* This array will hold all the structs */ + Request[] requests; + + + /** + * @dev This event will be emitted when there is need to update the Fish data + * @dev Which will cause oracle script, who listen for this event, to respond + * @dev Which will then call reply() function with valid parameters which will be unpdate in smart contract + * @dev parameter will be requet ID used to validate the each request + */ + event NewRequest(); + + + /** + * @dev This function will be called to request data from outside source + * @dev It will emit event for oracles + * + * + */ + function queryOracle() public { + emit NewRequest(); + } + + /** + * @dev This function will be called by the Oracle to supply the data to update the smart contract + * @dev To check validity of the response, we will be making sure the caller must be owner + * + * @param fishQualityNew The quality of the fish, data provided by Oracle + * @param fishQuantityNew The quantity of the fish, data provided by Oracle + * @param deliveryDateNew The delivery date of the fish, data provided by Oracle + */ + function responseFromOracle(bool fishQualityNew, uint256 fishQuantityNew, uint256 deliveryDateNew) public onlyOwner { + + //validate the incoming data + require(fishQuantityNew > 0 && fishQuantityNew <= 5); + require(deliveryDateNew > 0 && deliveryDateNew <= 999999999999999999); //this is to prevent over flow or under flow + + // update the fish data + fishQuality = fishQualityNew; + fishQuantity = fishQuantityNew; + deliveryDate = deliveryDateNew; + + // adding those data into an struct and array for the logging purpose + requests.push(Request(fishQualityNew, fishQuantityNew, deliveryDateNew)); + } + + + } + + + +//*********************************************************************// +//------------------ FishTrade Contract Starts Here -------------------// +//*********************************************************************// + + contract FishTrade is owned, Oracle { + + /***********************************/ + /* Use case of Fish Trade */ + /***********************************/ + + + /** + * @dev Payable function. As for our case, it will only accept 12 Ether + * @dev Buyer (person A) will send money to escrow using this function + * @dev Buyer also have to specify the Seller address + * @dev The reason to specify Seller is because it will tag to this trade. + * @dev So, when buyer will release escrow, then fund will be transfered to seller + * + * @param _seller The address of seller + */ + function buyerDeposit(address _seller) payable public { + require(msg.value == 12 ether, 'Ether value must be 12 Ether'); + payToEscrow(_seller); + } + + + /** + * @dev This function must be called by seller to check if buyer has deposited 12 ether + * + * @param _buyer The address of the buyer + * @param _seller The address of the seller + * @param timestamp The timestamp of the trade. + * @param ethAmountWEI The amount of ether in WEI + * + * @return bool true or false, whether buyer paid or not + */ + function paymentConfirmationCheck(address _buyer, address _seller, uint256 timestamp, uint256 ethAmountWEI) public view returns(bool paid) { + + /* Calculating the hash from given parameters */ + bytes32 hash = keccak256(abi.encodePacked(this, _buyer, _seller, timestamp, ethAmountWEI)); + + /* For our case, it should be 12 Ether */ + require( escrowBalance[_buyer][_seller][hash] == 12 ether , 'Transaction amount is zero. Most probably the input parameters are invalid.'); + + return paid; + + } + + /** + * @dev This function called by buyer (Person A) when the delivery arrives + * @dev The data of fish coming from the Oracle + * + * @dev If fish is not in good quality as well as delivery is not on time, then refund buyer + * @dev If delivery is right and buyer accepts it, then release escrow and payment sent to seller + * + * @param _seller Address of seller + * @param ethAmountWEI The amount of ether + * @param orderTimestamp The timestamp of order + * + */ + function fishDelivered( address payable _seller, uint256 ethAmountWEI, uint256 orderTimestamp ) public { + + /* Getting fish data updates from Oracle */ + queryOracle(); + + /* If A reports that the fish is not of good quality in 2 hours, A will get his money back from the escrow. */ + if(fishQuality == false){ //false means no good! + refundBuyer(_seller, ethAmountWEI, orderTimestamp); + } + + /* If the fish does not get delivered to A in time, that means not on the 1st of February 2019, A will get his money back from the escrow. */ + if(deliveryDate != 1548979200){ //1548979200 = 01 Feb 2019 00:00:00 + refundBuyer(_seller, ethAmountWEI, orderTimestamp); + } + + /* If delivery is right, and buyer (person A) accept it then payment sent to seller (Person B) */ + if(isRightDelivery()){ + releaseEscrow(msg.sender, address(_seller), orderTimestamp, ethAmountWEI); + } + + } + + + /** + * @dev This function called by seller (Person B) when buyer (Person A) does not accept the delivery + * @dev Escrow is relased and seller (Person B) gets the money + * + * @param _buyer Address of buyer + * @param ethAmountWEI The amount of ether + * @param orderTimestamp The timestamp of order + */ + function deliveryNotAccepted(address _buyer, uint256 ethAmountWEI, uint256 orderTimestamp) public { + releaseEscrow(_buyer, msg.sender, orderTimestamp, ethAmountWEI); + } + + + /** + * @dev This function checks whether delivery is right or not + * @dev It considers the data updated by the Oracle + * + * @return bool returns whether this is right delivery or not + */ + function isRightDelivery() internal view returns(bool) { + + /* Fish quantity must be true=good */ + if(fishQuality != true){ + return false; + } + + /* Fish quantity must be 5 Kg */ + else if(fishQuantity != 5){ + return false; + } + + /* Delivery date must be 01 Feb 2019 */ + else if(deliveryDate != 1548979200){ //01 Feb 2019 00:00:00 + return false; + } + + /* The deivery is right then return true */ + else{ + return true; + } + } + + + + /*********************************/ + /* Section for Escrow */ + /*********************************/ + + /* Mapping which will map buyer address with seller, unique transaction hash and their ETH amount */ + mapping (address => mapping (address => mapping (bytes32 => uint256))) public escrowBalance; + + /* Events which logs all the transactions */ + event EscrowDeposit(address buyer, address seller, uint256 ethAmount, uint256 timestamp, bytes32 txnHash ); + event ReleaseEscrow(address buyer, address seller, uint256 ethAmount, uint256 timestamp, bytes32 txnHash ); + + /** + * @dev Buyer will send money to escrow using this function + * @dev To make every transaction unique, we will create a simple transaction ID + * + * @param _seller The address of the seller, which should be specified by buyer + * @return success Whether payment to escrow was a success or not + */ + function payToEscrow(address _seller) internal { + + /* Validating the user input */ + require(msg.value > 0, 'Ether amount must be more than zero'); + require(_seller != address(0), 'Seller address is invalid'); + + /* Calculating the transaction has from the user inputf */ + bytes32 hash = keccak256(abi.encodePacked(this, msg.sender, _seller, now, msg.value)); + + /* Adds the amount in Escrow balance mappubg */ + escrowBalance[msg.sender][_seller][hash] = msg.value; + + /* Emitting the event */ + emit EscrowDeposit(msg.sender, _seller, msg.value, now, hash ); + + } + + + /** + * Once Fishes received, then buyer will release escrow + * It will calculate the transaction hash again from the input parameter to verify the transaction + * + * @param _buyer The address of the buyer + * @param _seller The address of the seller + * @param ethAmountWEI The amount of ether in WEI + * @param timestamp The timestamp of the trade. + * + */ + function releaseEscrow(address _buyer, address payable _seller, uint256 timestamp, uint256 ethAmountWEI) internal { + + /* Calculating the hash from given parameters */ + bytes32 hash = keccak256(abi.encodePacked(this, _buyer, _seller, timestamp, ethAmountWEI)); + + require( escrowBalance[_buyer][_seller][hash] > 0 , 'Transaction amount is zero. Most probably the input parameters are invalid.'); + + /* Setting Escrow amount to zerp */ + escrowBalance[_buyer][_seller][hash] = 0; + + /* Transferring the ETH to seller */ + address(_seller).transfer(ethAmountWEI); + + /* Emitting the event */ + emit ReleaseEscrow(msg.sender, _seller, ethAmountWEI, timestamp, hash ); + + } + + + function refundBuyer(address _seller, uint256 ethAmountWEI, uint256 timestamp) public { + + /* Calculating the hash from given parameters */ + bytes32 hash = keccak256(abi.encodePacked(this, msg.sender, _seller, timestamp, ethAmountWEI)); + + require( escrowBalance[msg.sender][_seller][hash] > 0 , 'Transaction amount is zero. Most probably the input parameters are invalid.'); + + /* Setting Escrow amount to zerp */ + escrowBalance[msg.sender][_seller][hash] = 0; + + /* Transferring the ETH to seller */ + address(msg.sender).transfer(ethAmountWEI); + + /* Emitting the event */ + emit ReleaseEscrow(msg.sender, _seller, ethAmountWEI, timestamp, hash ); + + } + + + + +} + + + diff --git a/PoC/SSL Certificate Authority Management.sol b/PoC/SSL Certificate Authority Management.sol new file mode 100644 index 0000000..fdb1ec1 --- /dev/null +++ b/PoC/SSL Certificate Authority Management.sol @@ -0,0 +1,313 @@ +pragma solidity 0.5.2; /* + + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + ██████╗ █████╗ ██████╗ █████╗ ████████╗ █████╗ + ██╔════╝██╔══██╗ ██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗ + ██║ ███████║ █████╗ ██║ ██║███████║ ██║ ███████║ + ██║ ██╔══██║ ╚════╝ ██║ ██║██╔══██║ ██║ ██╔══██║ + ╚██████╗██║ ██║ ██████╔╝██║ ██║ ██║ ██║ ██║ + ╚═════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ + + + +THE MAIN LOGIC: + +Certificate Authorities (CAs) will be triggered when a 3 type of Process Type (Revoked, Hold, Unhold) is occurred. +All CAs needs to have a blockchain access in order to write/read data to/from blockchain network. +A user certificate can be revoked, holded and unholded if user request it from CA (It’s not our business). +Our project is starts on this point. When CA triggered for “revoked, holded and unholded” certificate status, CAs will send some information to the Blockchain Platform. + + +THE MAIN COMPONENT OF THE DATA + +(1) CA ID: This value will hold CA Certificate ID. It shows that which CA sended this data to the blockchain. + +(2) Certificate Serial No: This value represent serial number for certificate owner. +(3) Date:Process Date +(4) Process Type: 4 type of certificates will be hold on the blockchain. We will hold a number on this colomn. + 1 => Revoke + 2 => Hold + 3 => Unhold + 4 => Initia certificate issue +(5) Process Reason: This colomn represents process reason. We will hold a number on this column. + 0 => Unknown + 1 => Stolen + 2 => Information Change + 3 => CA Key Stolen + 4 => Get Instead + 5 => Break for a while + 6 => Hold + 7 => Unhold + 8 => Claims + 9 => Initial certificate issue + + +*/ + + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address public owner; + + constructor () public { + owner = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + function transferOwnership(address newOwner) onlyOwner public { + owner = newOwner; + } +} + + + +//*********************************************************************// +//------------------ CA Data Contract Starts Here -------------------// +//*********************************************************************// + +contract CA_Data is owned { + + /****************************************/ + /* Public Variables of CA Data */ + /****************************************/ + + /* Mapping which will hold CA wallet address and return if they are true or false */ + mapping(address => bool) public caWallets; + + /* An array which will hold wallet addresses of all the CAs, as well as mapping which holds index of each array element */ + address[] public caWalletsList; + mapping(address => uint256) public caWalletsListIndex; + mapping(address => string) public caWalletToID; + + /* Struct which holds Certificate Data for any particular certificate ID */ + struct CertificateDataIndividual { + uint256 certificateID; + string domainName; + address caWallet; + string caID; + uint256 date; + uint256 processType; + uint256 processReason; + } + + /* Mapping that maps particular CA ID to certificate ID with struct CertificateDataIndividual */ + mapping (string => mapping(uint256 => CertificateDataIndividual)) certificateDataAll; + + + + /* Events which logs all the transaction data and display to GUI */ + event CertificateData( + uint256 certificateID, + string domainName, + address indexed caWallet, + string caID, + uint256 date, + uint256 processType, + uint256 processReason + ); + + /* Modifier which requires only CA Caller */ + modifier onlyCA { + require(caWallets[msg.sender]); + _; + } + + /** + * @dev constructor function which will run only once while deploying the contract + * @dev we will assign all three CA wallet addresses now, which later can be removed by owner if required + */ + constructor() public { + + /* updating mapping caWallets */ + caWallets[0xef9EcD8a0A2E4b31d80B33E243761f4D93c990a8] = true; + caWallets[0x0086f09Bb9902839bFcE136F8D3c23794dcfDF40] = true; + caWallets[0x7eF8A233AC746Ea398DED8B0536C83F55FcfCa1F] = true; + + /* adding all those addresses in caWalletsList Array */ + caWalletsList.push(0xef9EcD8a0A2E4b31d80B33E243761f4D93c990a8); + caWalletsList.push(0x0086f09Bb9902839bFcE136F8D3c23794dcfDF40); + caWalletsList.push(0x7eF8A233AC746Ea398DED8B0536C83F55FcfCa1F); + + /* Updating caWalletsListIndex mapping to index all those array element */ + caWalletsListIndex[0xef9EcD8a0A2E4b31d80B33E243761f4D93c990a8] = 0; + caWalletsListIndex[0x0086f09Bb9902839bFcE136F8D3c23794dcfDF40] = 1; + caWalletsListIndex[0x7eF8A233AC746Ea398DED8B0536C83F55FcfCa1F] = 2; + + /* adding IDs of respective CA Wallet address */ + caWalletToID[0xef9EcD8a0A2E4b31d80B33E243761f4D93c990a8] = "CAID1"; + caWalletToID[0x0086f09Bb9902839bFcE136F8D3c23794dcfDF40] = "CAID2"; + caWalletToID[0x7eF8A233AC746Ea398DED8B0536C83F55FcfCa1F] = "CAID3"; + } + + + /****************************************/ + /* CA Only Functions */ + /****************************************/ + + /** + * @dev This function called by CA only to issue certificate for very first time + * @dev CA provides following details + * + * @param certificateID_ Unique numeric ID of the certificate + * @param domainName_ Name of the domain for which certificate to be issued + * @param issueDate_ Date of initial issue + * + * @return bool Returns true for successful transaction + */ + function issueCertificate( + uint256 certificateID_, + string memory domainName_, + uint256 issueDate_ + ) onlyCA public returns(bool) { + string storage caID = caWalletToID[msg.sender]; + require(certificateDataAll[caID][certificateID_].certificateID == 0, 'Certificate ID is already used'); + certificateDataAll[caID][certificateID_] = CertificateDataIndividual({ + certificateID: certificateID_, + domainName: domainName_, + caWallet: msg.sender, + caID: caID, + date: issueDate_, + processType: 4, // 4 is default status code for initial issue of certificate + processReason: 9 // 9 is default reason code for initial issue of certificate + }); + + emit CertificateData( + certificateID_, + domainName_, + msg.sender, + caWalletToID[msg.sender], + issueDate_, + 4, + 9 + ); + + return true; + } + + + /** + * @dev This function called by CA only to update certificate for any domain + * @dev CA provides following details + * + * @param processType_ Type of transaction. It would be from 1-9 as status code + * @return bool Returns true for successful transaction + */ + function updateCertificate( + uint256 certificateID_, + uint256 processType_, + uint256 processReason_ + ) onlyCA public returns(bool) { + string storage caID = caWalletToID[msg.sender]; + require(certificateDataAll[caID][certificateID_].certificateID == certificateID_, 'Certificate ID does not exist'); + require(certificateDataAll[caID][certificateID_].caWallet == msg.sender, 'Caller is not authorised CA'); + + certificateDataAll[caID][certificateID_].date = now; + certificateDataAll[caID][certificateID_].processType = processType_; + certificateDataAll[caID][certificateID_].processReason = processReason_; + + emit CertificateData( + certificateID_, + certificateDataAll[caID][certificateID_].domainName, + certificateDataAll[caID][certificateID_].caWallet, + certificateDataAll[caID][certificateID_].caID, + certificateDataAll[caID][certificateID_].date, + certificateDataAll[caID][certificateID_].processType, + certificateDataAll[caID][certificateID_].processReason + ); + + return true; + } + + + /****************************************/ + /* Users read only functions */ + /****************************************/ + + /** + * @dev Users can loop up for any certificate information using its certificate ID + * @param certificateID_ The certificate ID + * @return All the information of struct for that particular certificate ID + * + */ + function lookUpCertificate(uint256 certificateID_, string memory _caID) public view returns(uint256, string memory, string memory, uint256, uint256, uint256){ + return ( + certificateDataAll[_caID][certificateID_].certificateID, + certificateDataAll[_caID][certificateID_].domainName, + certificateDataAll[_caID][certificateID_].caID, + certificateDataAll[_caID][certificateID_].date, + certificateDataAll[_caID][certificateID_].processType, + certificateDataAll[_caID][certificateID_].processReason + ); + } + + /** + * @dev Function to see all the CAs authorised to write in the smart contract + * @return address[] An array of all the CA addresses + */ + function seeALLCA() public view returns (address[] memory){ + return caWalletsList; + } + + + /****************************************/ + /* Owner only functions */ + /****************************************/ + + /** + * @dev Owner can add new CA wallet, who then can write data in the smart contract + * @dev It will check if CA already exist or not + * @param caWalletAddress New wallet address of the CA + * @return bool Returns true for successful transaction + */ + function addNewCA(address caWalletAddress, string memory caID) onlyOwner public returns(bool){ + + require(caWalletAddress != address(0), 'Address is invalid'); + require(!caWallets[caWalletAddress], 'CA is already exist'); + + caWallets[caWalletAddress] = true; + caWalletToID[caWalletAddress] = caID; + caWalletsList.push(caWalletAddress); + caWalletsListIndex[caWalletAddress] = caWalletsList.length-1; + + return true; + } + + /** + * @dev Owner can remove any CA from the system + * @dev It will remove CA address from the mapping as well as from the Array along with its index mapping + * @param caWalletAddress The wallet address of the CA + * @return bool Returns true for successful transaction + */ + function removeAnyCA(address caWalletAddress) onlyOwner public returns(bool){ + + require(caWalletAddress != address(0), 'Address is invalid'); + require(caWallets[caWalletAddress], 'CA does not exist'); + + caWallets[caWalletAddress] = false; + caWalletToID[caWalletAddress] = ""; + caWalletsList[caWalletsListIndex[caWalletAddress]] = caWalletsList[caWalletsList.length-1]; + caWalletsListIndex[caWalletsList[caWalletsList.length-1]] = caWalletsListIndex[caWalletAddress]; + caWalletsListIndex[caWalletAddress]=0; + caWalletsList.length--; + return true; + } + + +} diff --git a/Stable Coin/True INR Stable coin.sol b/Stable Coin/True INR Stable coin.sol new file mode 100644 index 0000000..fab3d9a --- /dev/null +++ b/Stable Coin/True INR Stable coin.sol @@ -0,0 +1,643 @@ +pragma solidity 0.5.3; /* + + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + ████████╗██████╗ ██╗ ██╗███████╗ ██╗███╗ ██╗██████╗ + ╚══██╔══╝██╔══██╗██║ ██║██╔════╝ ██║████╗ ██║██╔══██╗ + ██║ ██████╔╝██║ ██║█████╗ ██║██╔██╗ ██║██████╔╝ + ██║ ██╔══██╗██║ ██║██╔══╝ ██║██║╚██╗██║██╔══██╗ + ██║ ██║ ██║╚██████╔╝███████╗ ██║██║ ╚████║██║ ██║ + ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ + + +// ---------------------------------------------------------------------------- +// 'True INR' Stable coin contract with following features +// => ERC20 Compliance +// => Higher degree of control by owner - safeguard functionality +// => SafeMath implementation +// => Upgradeability using Unstructured Storage +// +// Name : True INR +// Symbol : TINR +// Initial supply : 0 (Stable coin for INR) +// Decimals : 18 +// +// Copyright (c) 2019 onwards True INR Inc. ( https://trueINR.io ) +// Contract designed by EtherAuthority ( https://EtherAuthority.io ) +// Special thanks to openzeppelin for inspiration: +// https://github.com/zeppelinos/labs/tree/master/upgradeability_using_unstructured_storage +// ---------------------------------------------------------------------------- + +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } +} + + +//*******************************************************************// +//--------------- Contract to Manage Ownership/Admins ---------------// +//*******************************************************************// +// // +// Owener is set while deploying this contract as well as.. // +// When this contract is used as implementation by the proxy contract// +// // +//-------------------------------------------------------------------// +contract owned { + //public variables of owner and admins + address payable public owner; + address payable public admin1; + address payable public admin2; + + //constructor has not any use as all this values to be assign while Initialize function by proxy contract + constructor () public {} + + //modifier for only owner + modifier onlyOwner { + require(msg.sender == owner); + _; + } + + //modifier for admins + modifier onlyAdmins { + require(msg.sender == admin1 || msg.sender == admin2); + _; + } + + //function to transfer ownership. only owner can do this + function transferOwnership(address payable newOwner) onlyOwner public { + owner = newOwner; + } + + //function to change admins only owner can do that + function changeAdmin(address payable newAdmin1, address payable newAdmin2) onlyOwner public { + //addresses are not checked agains 0x0 because owner can add 0x0 as to remove admin + admin1 = newAdmin1; + admin2 = newAdmin2; + } + +} + + + +//***************************************************************// +//------------------ ERC20 Standard Template -------------------// +//***************************************************************// + +contract TokenERC20 { + // Public variables of the token + using SafeMath for uint256; + string public name; + string public symbol; + uint256 public decimals; + uint256 public totalSupply; + bool public safeguard; //putting safeguard on will halt all non-owner functions + + // This creates an array with all balances + mapping (address => uint256) public balanceOf; + mapping (address => mapping (address => uint256)) public allowance; + + // This generates a public transfer event on the blockchain that will notify clients + event Transfer(address indexed from, address indexed to, uint256 value); + + // This notifies clients about the amount burnt and mint + event Burn(address indexed from, uint256 value); + event Mint(address indexed minter, address indexed receiver, uint256 value); + + /** + * Constrctor function + */ + constructor () public {} + + /** + * Internal transfer, only can be called by this contract + */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + // Prevent transfer to 0x0 address. Use burn() instead + require(_to != address(0x0)); + // Check if the sender has enough + require(balanceOf[_from] >= _value); + // Check for overflows + require(balanceOf[_to].add(_value) > balanceOf[_to]); + // Save this for an assertion in the future + uint previousBalances = balanceOf[_from].add(balanceOf[_to]); + // Subtract from the sender + balanceOf[_from] = balanceOf[_from].sub(_value); + // Add the same to the recipient + balanceOf[_to] = balanceOf[_to].add(_value); + emit Transfer(_from, _to, _value); + // Asserts are used to use static analysis to find bugs in your code. They should never fail + assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); + } + + /** + * Transfer tokens + * + * Send `_value` tokens to `_to` from your account + * + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transfer(address _to, uint256 _value) public returns (bool success) { + _transfer(msg.sender, _to, _value); + return true; + } + + /** + * Transfer tokens from other address + * + * Send `_value` tokens to `_to` in behalf of `_from` + * + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value the amount to send + */ + function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { + require(!safeguard); + require(_value <= allowance[_from][msg.sender]); // Check allowance + allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); + _transfer(_from, _to, _value); + return true; + } + + /** + * Set allowance for other address + * + * Allows `_spender` to spend no more than `_value` tokens in your behalf + * + * @param _spender The address authorized to spend + * @param _value the max amount they can spend + */ + function approve(address _spender, uint256 _value) public + returns (bool success) { + require(!safeguard); + allowance[msg.sender][_spender] = _value; + return true; + } + +} + +//********************************************************************************// +//------------------ TRUE INR VERSION I - MAIN CODE STARTS HERE -----------------// +//********************************************************************************// + +contract TrueINR_v1 is owned, TokenERC20 { + + + /****************************************/ + /* Custom Code for the ERC20 TINR Token */ + /****************************************/ + + /* Storage variables for mint hold, which does by admins */ + struct MintHold { + address user; + uint256 tokenAmount; + uint256 releaseTimeStamp; + } + MintHold[] public mintHoldArray; + MintHold[] internal tempArray; + + + + /* Records for the fronzen accounts */ + mapping (address => bool) public frozenAccount; + + /* This generates a public event on the blockchain that will notify clients */ + event FrozenFunds(address target, bool frozen); + + /* Initializes contract with constructor function */ + constructor () TokenERC20() public {} + + /* Internal transfer, only can be called by this contract */ + function _transfer(address _from, address _to, uint _value) internal { + require(!safeguard); + require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead + require(!frozenAccount[_from]); // Check if sender is frozen + require(!frozenAccount[_to]); // Check if recipient is frozen + balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender + balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient + emit Transfer(_from, _to, _value); + } + + /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens + /// @param target Address to be frozen + /// @param freeze either to freeze it or not + function freezeAccount(address target, bool freeze) public { + require(msg.sender == owner || msg.sender == admin1 || msg.sender == admin2, 'Unauthorised caller'); + frozenAccount[target] = freeze; + emit FrozenFunds(target, freeze); + } + + /** + * @dev Function to mint tokens + * @param _to The address that will receive the minted tokens. + * @param _amount The amount of tokens to mint. + * @return A boolean that indicates if the operation was successful. + */ + function mint(address _to, uint256 _amount) public returns (bool) { + require(_to != address(0)); + //require(_amount > 0); this is useless because solidity uint256 does not allow negative number + + //if owner is calling mint function, then it will generate tokens immediately + if(msg.sender == owner){ + totalSupply = totalSupply.add(_amount); + balanceOf[_to] = balanceOf[_to].add(_amount); + + emit Mint(msg.sender, _to, _amount); + emit Transfer(address(0), _to, _amount); + } + else if(msg.sender == admin1 || msg.sender == admin2){ + //release time will be 12 hours from now + mintHoldArray.push(MintHold(_to, _amount, now + 43200)); + } + else{ + revert(); + } + + return true; + } + + + + /** + * Release hold mint tokens and sent to reciepient. Owner and admins only can do this. + */ + function releaseMint() public returns(bool){ + require(msg.sender == owner || msg.sender == admin1 || msg.sender == admin2, 'Unauthorised caller'); + //it will check all the pending entries and whose time has come, will be released + uint256 totalHoldTransactions = mintHoldArray.length; + for(uint256 i=0; i < totalHoldTransactions; i++ ){ + //it will check if the release date is passed or not + if(mintHoldArray[i].releaseTimeStamp < now){ + + //process the token Transfer + totalSupply = totalSupply.add(mintHoldArray[i].tokenAmount); + balanceOf[mintHoldArray[i].user] = balanceOf[mintHoldArray[i].user].add(mintHoldArray[i].tokenAmount); + + //emit events for logging purpose + emit Mint(msg.sender, mintHoldArray[i].user, mintHoldArray[i].tokenAmount); + emit Transfer(address(0), mintHoldArray[i].user, mintHoldArray[i].tokenAmount); + + //to avoid gas limit max out, we want to restrict max elements processed by 10 at a time. + //admin or owner can do multiple transactions to process more elements. + if(i >= 10){ break; } + + } + else{ + //if any entry which is not ready for the release, will be added to temporary array which later will be replaced with the main array + tempArray.push(MintHold(mintHoldArray[i].user, mintHoldArray[i].tokenAmount, mintHoldArray[i].releaseTimeStamp )); + } + } + + //once all the entries either released or put on tempArray, then we will replace main array + mintHoldArray = tempArray; + + //then empty the tempArray for the next round + delete tempArray; + + return true; + } + + /** + * This function will cencel any hold mint tokens. this can be called by onlyOwner + */ + function cancelHoldMint(uint256 _index) public onlyOwner returns(bool){ + + mintHoldArray[_index] = mintHoldArray[mintHoldArray.length-1]; + mintHoldArray.pop(); + + return true; + } + + /** + * Reclaiming tokens from any users. This is for government regulation purpose. + */ + function reclaimTokens(address _user, uint256 _tokens) public returns(bool){ + + require(_user != address(0), 'Invalid address'); + require(msg.sender == owner || msg.sender == admin1 || msg.sender == admin2, 'Unauthorised caller'); + + //transfer the tokens from user to owner + _transfer(_user, owner, _tokens); + + return true; + + } + + + /** + * Destroy tokens. Only owner can call this. owner can burn tokens from any user account + * + * Remove `_value` tokens from the system irreversibly. It must be in decimal + * + * @param _value the amount of money to burn + */ + function burnFrom(address _burner, uint256 _value) public onlyOwner returns (bool success) { + //removes tokens from any users (burner). Data validation and Integer overflows handled by SafeMath + balanceOf[_burner] = balanceOf[_burner].sub(_value); + //updates totalSupply + totalSupply = totalSupply.sub(_value); + //emit event for logging purpose + emit Burn(msg.sender, _value); + return true; + } + + /** + * shows total number of hold/pending mint transactions + */ + function totalMintHoldTransactions()public view returns(uint256){ + return mintHoldArray.length; + } + + + /** + * Change safeguard status on or off + * + * When safeguard is true, then all the non-owner functions will stop working. + * When safeguard is false, then all the functions will resume working back again! + */ + function changeSafeguardStatus() onlyOwner public{ + if (safeguard == false){ + safeguard = true; + } + else{ + safeguard = false; + } + } + + /********************************************/ + /* Custom Code for the contract Upgradation */ + /********************************************/ + + bool internal initialized; + function initialize( + string memory _name, + string memory _symbol, + uint8 _decimals, + address payable _owner, + address payable _admin1, + address payable _admin2 + ) public { + require(!initialized); + require(_owner != address(0)); + require(owner == address(0)); //When this methods called, then owner address must be zero + + name = _name; + symbol = _symbol; + decimals = _decimals; + owner = _owner; + admin1 = _admin1; + admin2 = _admin2; + initialized = true; + } + + +} + + + +//********************************************************************************// +//---------------------- MAIN PROXY CONTRACTS SECTION STARTS --------------------// +//********************************************************************************// + + +/****************************************/ +/* Proxy Contract */ +/****************************************/ +/** + * @title Proxy + * @dev Gives the possibility to delegate any call to a foreign implementation. + */ +contract Proxy { + /** + * @dev Tells the address of the implementation where every call will be delegated. + * @return address of the implementation to which it will be delegated + */ + function implementation() public view returns (address); + + /** + * @dev Fallback function allowing to perform a delegatecall to the given implementation. + * This function will return whatever the implementation call returns + */ + function () payable external { + address _impl = implementation(); + require(_impl != address(0)); + + 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) } + } + } +} + + +/****************************************/ +/* UpgradeabilityProxy Contract */ +/****************************************/ +/** + * @title UpgradeabilityProxy + * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded + */ +contract UpgradeabilityProxy is Proxy { + /** + * @dev This event will be emitted every time the implementation gets upgraded + * @param implementation representing the address of the upgraded implementation + */ + event Upgraded(address indexed implementation); + + // Storage position of the address of the current implementation + bytes32 private constant implementationPosition = keccak256("EtherAuthority.io.proxy.implementation"); + + /** + * @dev Constructor function + */ + constructor () public {} + + /** + * @dev Tells the address of the current implementation + * @return address of the current implementation + */ + function implementation() public view returns (address impl) { + bytes32 position = implementationPosition; + assembly { + impl := sload(position) + } + } + + /** + * @dev Sets the address of the current implementation + * @param newImplementation address representing the new implementation to be set + */ + function setImplementation(address newImplementation) internal { + bytes32 position = implementationPosition; + assembly { + sstore(position, newImplementation) + } + } + + /** + * @dev Upgrades the implementation address + * @param newImplementation representing the address of the new implementation to be set + */ + function _upgradeTo(address newImplementation) internal { + address currentImplementation = implementation(); + require(currentImplementation != newImplementation); + setImplementation(newImplementation); + emit Upgraded(newImplementation); + } +} + +/****************************************/ +/* OwnedUpgradeabilityProxy contract */ +/****************************************/ +/** + * @title OwnedUpgradeabilityProxy + * @dev This contract combines an upgradeability proxy with basic authorization control functionalities + */ +contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { + /** + * @dev Event to show ownership has been transferred + * @param previousOwner representing the address of the previous owner + * @param newOwner representing the address of the new owner + */ + event ProxyOwnershipTransferred(address previousOwner, address newOwner); + + // Storage position of the owner of the contract + bytes32 private constant proxyOwnerPosition = keccak256("EtherAuthority.io.proxy.owner"); + + /** + * @dev the constructor sets the original owner of the contract to the sender account. + */ + constructor () public { + setUpgradeabilityOwner(msg.sender); + } + + /** + * @dev Throws if called by any account other than the owner. + */ + modifier onlyProxyOwner() { + require(msg.sender == proxyOwner()); + _; + } + + /** + * @dev Tells the address of the owner + * @return the address of the owner + */ + function proxyOwner() public view returns (address owner) { + bytes32 position = proxyOwnerPosition; + assembly { + owner := sload(position) + } + } + + /** + * @dev Sets the address of the owner + */ + function setUpgradeabilityOwner(address newProxyOwner) internal { + bytes32 position = proxyOwnerPosition; + assembly { + sstore(position, newProxyOwner) + } + } + + /** + * @dev Allows the current owner to transfer control of the contract to a newOwner. + * @param newOwner The address to transfer ownership to. + */ + function transferProxyOwnership(address newOwner) public onlyProxyOwner { + require(newOwner != address(0)); + emit ProxyOwnershipTransferred(proxyOwner(), newOwner); + setUpgradeabilityOwner(newOwner); + } + + /** + * @dev Allows the proxy owner to upgrade the current version of the proxy. + * @param implementation representing the address of the new implementation to be set. + */ + function upgradeTo(address implementation) public onlyProxyOwner { + _upgradeTo(implementation); + } + + /** + * @dev Allows the proxy owner to upgrade the current version of the proxy and call the new implementation + * to initialize whatever is needed through a low level call. + * @param implementation representing the address of the new implementation to be set. + * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function + * signature of the implementation to be called with the needed payload + */ + function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner { + _upgradeTo(implementation); + (bool success,) = address(this).call.value(msg.value).gas(200000)(data); + require(success,'initialize function errored'); + } + + function returnInitialiseData(string memory name, string memory symbol, uint8 decimals, address payable owner ) public pure returns(bytes memory){ + + return abi.encodeWithSignature("initialize(string,string,uint8,address,address,address)",name,symbol,decimals,owner,owner,owner); + + + } +} + + +/****************************************/ +/* TrueINRProxy Contract */ +/****************************************/ + +/** + * @title TrueINR_proxy + * @dev This contract proxies FiatToken calls and enables FiatToken upgrades +*/ +contract TrueINR_proxy is OwnedUpgradeabilityProxy { + constructor() public OwnedUpgradeabilityProxy() { + } +} diff --git a/Staking/Diamond Dividend Trontopia.sol b/Staking/Diamond Dividend Trontopia.sol new file mode 100644 index 0000000..9f85b49 --- /dev/null +++ b/Staking/Diamond Dividend Trontopia.sol @@ -0,0 +1,515 @@ +pragma solidity 0.4.25; /* + +___________________________________________________________________ + _ _ ______ + | | / / / +--|-/|-/-----__---/----__----__---_--_----__-------/-------__------ + |/ |/ /___) / / ' / ) / / ) /___) / / ) +__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ + + + + +████████╗ ██████╗ ██████╗ ██╗ █████╗ ███╗ ██╗███████╗████████╗██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗ +╚══██╔══╝██╔═══██╗██╔══██╗██║██╔══██╗ ████╗ ██║██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔══██╗██║ ██╔╝ + ██║ ██║ ██║██████╔╝██║███████║ ██╔██╗ ██║█████╗ ██║ ██║ █╗ ██║██║ ██║██████╔╝█████╔╝ + ██║ ██║ ██║██╔═══╝ ██║██╔══██║ ██║╚██╗██║██╔══╝ ██║ ██║███╗██║██║ ██║██╔══██╗██╔═██╗ + ██║ ╚██████╔╝██║ ██║██║ ██║ ██║ ╚████║███████╗ ██║ ╚███╔███╔╝╚██████╔╝██║ ██║██║ ██╗ + ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ + + + +=== 'Diamond Vouchers Dividend' contract with following features === + => Higher degree of control by owner + => All frozen diamonds will get dividend + => SafeMath implementation + + + +------------------------------------------------------------------- + Copyright (c) 2019 onwards Topia Network Inc. ( https://topia.network ) + Contract designed with ❤ by EtherAuthority ( https://EtherAuthority.io ) +------------------------------------------------------------------- +*/ + +//*******************************************************************// +//------------------------ SafeMath Library -------------------------// +//*******************************************************************// +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + require(c / a == b, 'SafeMath mul failed'); + return c; + } + + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + require(b <= a, 'SafeMath sub failed'); + return a - b; + } + + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + require(c >= a, 'SafeMath add failed'); + return c; + } +} + + + +//**************************************************************************// +//--------------------- GAMES CONTRACT INTERFACE ---------------------// +//**************************************************************************// + +interface InterfaceGAMES { + function getAvailableDiamondRake() external returns (uint256); + function requestDiamondRakePayment() external returns(bool); +} + + +//**************************************************************************// +//--------------------- DIAMOND CONTRACT INTERFACE ---------------------// +//**************************************************************************// + +interface InterfaceDIAMOND { + function frozenDiamondsGlobal() external returns (uint256); + function usersDiamondFrozen(address user) external returns(uint256); + function transfer(address to, uint256 amount) external returns(bool); +} + + +//*******************************************************************// +//------------------ Contract to Manage Ownership -------------------// +//*******************************************************************// + +contract owned { + address internal owner; + address internal newOwner; + + /** + Signer is deligated admin wallet, which can do sub-owner functions. + Signer calls following four functions: + => request fund from game contract + */ + address internal signer; + + event OwnershipTransferred(address indexed _from, address indexed _to); + + constructor() public { + owner = msg.sender; + signer = msg.sender; + } + + modifier onlyOwner { + require(msg.sender == owner, 'caller must be owner'); + _; + } + + modifier onlySigner { + require(msg.sender == signer, 'caller must be signer'); + _; + } + + function changeSigner(address _signer) public onlyOwner { + signer = _signer; + } + + function transferOwnership(address _newOwner) public onlyOwner { + newOwner = _newOwner; + } + + //this flow is to prevent transferring ownership to wrong wallet by mistake + function acceptOwnership() public { + require(msg.sender == newOwner, 'caller must be new owner'); + emit OwnershipTransferred(owner, newOwner); + owner = newOwner; + newOwner = address(0); + } +} + + + + +//********************************************************************************// +//--------------------- DIAMOND DIVIDEND CODE STARTS HERE --------------------// +//********************************************************************************// + +contract DiamondDividend is owned { + + /*=============================== + = DATA STORAGE = + ===============================*/ + + // Public variables of the token + using SafeMath for uint256; + + address public voucherContractAddress; + address public diamondContractAddress; + bool public globalHalt; //when this variabe will be true, then safeguardTokenMovement will be true as well. Plus it will stop minting, which also stops game contracts! + + uint256 public dividendAccumulated; + uint256 public dividendRemainder; + uint256 public divPercentageSUN = 100000000; //100% of dividend distributed + uint256 public diamondsFrozenAtDivDistribution; //this tracks current total frozen token when dividend is distributed + uint256 public totalDividendsPaidNumber; //total number of dividends distributed. Mainly used with diamondsFrozenAtDivDistribution + uint256 public dividendPaidLastTime; + uint256 public divPaidAllTimeTrx; //tracks total number of div paid in trx + + + + // This creates a mapping with all data storage + mapping (address => bool) public whitelistCaller; + address[] public whitelistCallerArray; + mapping (address => uint256) internal whitelistCallerArrayIndex; + + + mapping (address => uint256) public previousDivAmountWithdrawal; //keeps track of dividend pool amount for user => token at time of div withdrawal + mapping(address => uint256) public totalFrozenDiamondTracker; //tracks totalFrozen diamonds at the time of user freeze token + mapping(address => uint256) public noOfDivPaidAfterFreeze; //tracks number of dividend distribution attempted after user froze + + + + + + /*=============================== + = PUBLIC EVENTS = + ===============================*/ + + + //DividendPaid by admin + event DividendPaidTRX(uint256 indexed totalDividendPaidTRX); + + //user withdraw dividend + event DividendWithdrawTRX(address indexed user, uint256 indexed tokenID, uint256 indexed amount); + + + + + + /*===================================== + = CUSTOM DIVIDEND FUNCTIONS = + ======================================*/ + + + /** + Constructor function. nothing happens + */ + constructor() public { + + //dividendPaidLastTime is set to deploy time as first dividend paid, so it works properly in distribute function + dividendPaidLastTime = now; + + + } + + /** + * Fallback function. It just accepts incoming TRX + */ + function () payable external {} + + /** + This function displays all the dividend of all the game contracts + */ + function getDividendPotential() public view returns(uint256){ + //we will check dividends of all the game contract individually + uint256 totalGameContracts = whitelistCallerArray.length; + uint256 totalDividend; + for(uint i=0; i < totalGameContracts; i++){ + uint256 amount = InterfaceGAMES(whitelistCallerArray[i]).getAvailableDiamondRake(); + if(amount > 0){ + totalDividend += amount; + } + } + + if(totalDividend > 0 || dividendAccumulated > 0 ){ + + //admin can set % of dividend to be distributed. + //reason for 1000000 is that divPercentageSUN was in SUN + uint256 newAmount = totalDividend * divPercentageSUN / 100 / 1000000; + + return newAmount + dividendAccumulated; + + } + + //by default it returns zero + + } + + + function distributeMainDividend() public onlySigner returns(string, uint256, uint256, uint256){ + + uint256 frozenDiamondsGlobal = InterfaceDIAMOND(diamondContractAddress).frozenDiamondsGlobal(); + + require(frozenDiamondsGlobal > 0, 'none has frozen diamonds'); + require(!globalHalt, 'Global Halt is on'); + + //signer can call this function anytime + //but if he does not call it after 7 days, then anyone can call this and distribute the dividend. + //this is to increase trust in player community. + if(msg.sender != signer){ + require(dividendPaidLastTime + 604800 < now, 'You need to wait 7 days to Do This'); + } + + + //we will check dividends of all the game contract individually + uint256 totalGameContracts = whitelistCallerArray.length; + uint256 totalDividend; + for(uint i=0; i < totalGameContracts; i++){ + address gameAddress = whitelistCallerArray[i]; + uint256 amount = InterfaceGAMES(gameAddress).getAvailableDiamondRake(); + if(amount > 0){ + //if status is true, which means particular game has positive dividend available + totalDividend += amount; + + //we will request that dividend TRX from game contract to this token contract + require(InterfaceGAMES(gameAddress).requestDiamondRakePayment(), 'could not transfer trx'); + } + } + + uint256 dividendAccumulatedLocal = dividendAccumulated; + if(totalDividend > 0 || dividendAccumulatedLocal > 0 ){ + + //admin can set % of dividend to be distributed. + //reason for 1000000 is that divPercentageSUN was in SUN + uint256 newAmount = totalDividend * divPercentageSUN / 100 / 1000000; + + //if dividend % is less than 100%, then track that remainder in another variable + if(divPercentageSUN < 100000000){ + dividendRemainder += totalDividend * (100000000 - divPercentageSUN) / 100 / 1000000; + } + + uint256 payableAmount = newAmount + dividendAccumulatedLocal; + + + //trackers to determine total dividend share for particular user who frozen token for specific period of time + divPaidAllTimeTrx += payableAmount; + diamondsFrozenAtDivDistribution += frozenDiamondsGlobal; + totalDividendsPaidNumber++; + + dividendPaidLastTime = now; + dividendAccumulated = 0; + + emit DividendPaidTRX(payableAmount); + + return ("Distro Success: (1) Total Fetched (2) Accumulated Dividend (3) Final Payable amount:", totalDividend, dividendAccumulatedLocal, payableAmount ); + + } + + + } + + /** + * This function also used to invest any TRX into dividend pool. + */ + function reInvestDividendRemainder() public payable onlyOwner returns(string){ + + require(dividendRemainder > 0 || msg.value > 0, 'Invalid amount'); + require(!globalHalt, 'Global Halt is on'); + + dividendAccumulated += dividendRemainder + msg.value; + dividendRemainder=0; + return "dividendRemainder is sent to div pool"; + } + + + + /** + users can see how much dividend is confirmed available to him to withdraw + */ + function userConfirmedDividendTRX(address user) public view returns(uint256){ + //if there are more dividend distribution after user has frozen token + //user is eligible to receive more dividends from all the distributions done after his last withdrawal + uint256 previousDivAmountWithdrawalLocal = previousDivAmountWithdrawal[user]; + uint256 usersDiamondFrozen = InterfaceDIAMOND(diamondContractAddress).usersDiamondFrozen(user); + + if(divPaidAllTimeTrx > previousDivAmountWithdrawalLocal && usersDiamondFrozen > 0){ + + //finding all the subsequent dividends distributed by admin + //we will get current mainDiviendPaidAllTime and deduct the snapshot of it taken by user at the time of last withdrawal + //all three below trackers can never be zero due to above condition + uint256 newDividendPoolAmount = divPaidAllTimeTrx - previousDivAmountWithdrawalLocal; + uint256 totalFrozenShares = diamondsFrozenAtDivDistribution - totalFrozenDiamondTracker[user]; + uint256 totalNoOfDivPaid = totalDividendsPaidNumber - noOfDivPaidAfterFreeze[user]; + + + //first calculating user share percentage = user freeze tokens * 100 / total frozen tokens + //the reason for the number 1000000, is to have sharePercentage variable have more decimals. + //so 1000000 is multiplied in sharePercentage,which was then divided in total amount in below equasion. + //(totalFrozenTopia / totalNoOfDivPaid) at the end is avearage of all topia fronzen at time of div distribution + uint256 sharePercentage = usersDiamondFrozen * 100 * 1000000 / (totalFrozenShares / totalNoOfDivPaid) ; + + + //now calculating final trx amount from ( available dividend pool * share percentage / 100) + if(newDividendPoolAmount * sharePercentage > 0){ + + return newDividendPoolAmount * sharePercentage / 100 / 1000000; + + } + + } + + //by default it will return zero + } + + + + /** + This function will withdraw dividends in TRX + divTracker variable means whether to update the dividend trackers or not, + as freeze token function will require update and unfreeze requires withdraw without updating dividend trackers + */ + function withdrawDividendsEverythingInternal(address user) internal returns(bool){ + + + //TRX withdraw + uint256 outstandingDivTRX = userConfirmedDividendTRX(user); + if(outstandingDivTRX > 0){ + user.transfer(outstandingDivTRX); + emit DividendWithdrawTRX(user, 0, outstandingDivTRX); + } + + return true; + } + + + /** + This function can be called by user directly or via any other contract + It will withdraw any outstanding token for any user and ALSO UPDATES dividend trackers + */ + function withdrawDividendsEverything() public returns(bool){ + + require(!globalHalt, 'Global Halt is on'); + + //tx.origin is because it will take original caller even if user is calling via another contract. + address user = tx.origin; + + //second param as true, meaning it will update the dividend tracker + require(withdrawDividendsEverythingInternal(user), 'withdraw dividend everything function did not work'); + + + //this will track the total frozen token at the time of freeze + //which will be used in calculating share percentage of div pool + totalFrozenDiamondTracker[user] = diamondsFrozenAtDivDistribution; + + //this will track all the dividend distribution attempts. + noOfDivPaidAfterFreeze[user] = totalDividendsPaidNumber; + + //TRX withdraw + previousDivAmountWithdrawal[user] = divPaidAllTimeTrx; + + + return true; + } + + + + + + + + /*===================================== + = HELPER FUNCTIONS = + ======================================*/ + + /** + * Add whitelist address who can call Mint function. Usually, they are other games contract + */ + function addWhitelistGameAddress(address _newAddress) public onlyOwner returns(string){ + + require(!whitelistCaller[_newAddress], 'No same Address again'); + + whitelistCaller[_newAddress] = true; + whitelistCallerArray.push(_newAddress); + whitelistCallerArrayIndex[_newAddress] = whitelistCallerArray.length - 1; + + return "Whitelisting Address added"; + } + + /** + * To remove any whilisted address + */ + function removeWhitelistGameAddress(address _address) public onlyOwner returns(string){ + + require(_address != address(0), 'Invalid Address'); + require(whitelistCaller[_address], 'This Address does not exist'); + + whitelistCaller[_address] = false; + uint256 arrayIndex = whitelistCallerArrayIndex[_address]; + address lastElement = whitelistCallerArray[whitelistCallerArray.length - 1]; + whitelistCallerArray[arrayIndex] = lastElement; + whitelistCallerArrayIndex[lastElement] = arrayIndex; + whitelistCallerArray.length--; + + return "Whitelisting Address removed"; + } + + + + function updateContractAddresses(address _voucherContract, address _diamondContract) public onlyOwner returns(string){ + voucherContractAddress = _voucherContract; + diamondContractAddress = _diamondContract; + return "voucher and diamond conract address updated successfully"; + } + + + + + /** + * Owner can transfer tokens from tonctract to owner address + */ + + function manualWithdrawTokens(address token, uint256 tokenAmount) public onlyOwner returns(string){ + // no need for overflow checking as that will be done in transfer function + InterfaceDIAMOND(token).transfer(owner, tokenAmount); + return "Tokens withdrawn to owner wallet"; + } + + + + + function manualWithdrawTRX(uint256 amount) public onlyOwner returns(string){ + owner.transfer(amount); + return "TRX withdrawn to owner wallet"; + } + + + + /** + * If global halt is off, then this funtion will on it. And vice versa + * This also change safeguard for token movement status + */ + function changeGlobalHalt() onlyOwner public returns(string) { + if (globalHalt == false){ + globalHalt = true; + } + else{ + globalHalt = false; + } + return "globalHalt status changed"; + } + + + + /** + * Function to check TRX balance in this contract + */ + function totalTRXbalanceContract() public view returns(uint256){ + return address(this).balance; + } + + + +} \ No newline at end of file diff --git a/Staking/HyperETH-Staking-Smart-Contract.sol b/Staking/HyperETH-Staking-Smart-Contract.sol new file mode 100644 index 0000000..e452eed --- /dev/null +++ b/Staking/HyperETH-Staking-Smart-Contract.sol @@ -0,0 +1,829 @@ +pragma solidity 0.5.4; + + +/** + * @title PoSTokenStandard + * @dev the interface of PoSTokenStandard + */ +contract PoSTokenStandard { + uint256 public stakeStartTime; + uint256 public stakeMinAge; + uint256 public stakeMaxAge; + function mint() public returns (bool); + function coinAge() public view returns (uint256); + function annualInterest() public view returns (uint256); + event Mint(address indexed _address, uint _reward); +} + +/*** + * https://hypereth.net + * + * No administrators or developers, this contract is fully autonomous + * + * 12 % entry fee + * 10 % of entry fee to masternode referrals + * 0 % transfer fee + * 15 % exit fee + * 1 % dividends fee on all the dividends balance + */ +contract HyperEX is PoSTokenStandard { + + using SafeMath for uint; + using SafeMath for uint256; + + /*================================= + = MODIFIERS = + =================================*/ + + /// @dev Only people with tokens + modifier onlyBagholders { + require(myTokens() > 0); + _; + } + + /// @dev Only people with profits + modifier onlyStronghands { + require(myDividends(true) > 0); + _; + } + + /// @dev notGasbag + modifier notGasbag() { + require(tx.gasprice < 200999999999); + _; + } + + /// @dev Preventing unstable dumping and limit ambassador mine + modifier antiEarlyWhale { + if (address(this).balance -msg.value < whaleBalanceLimit){ + require(msg.value <= maxEarlyStake); + } + if (depositCount_ == 0){ + require(ambassadors_[msg.sender] && msg.value == 0.001 ether); + }else + if (depositCount_ == 1){ + require(ambassadors_[msg.sender] && msg.value == 0.002 ether); + }else + if (depositCount_ == 2){ + require(ambassadors_[msg.sender] && msg.value == 0.003 ether); + } + _; + } + + /// @dev notGasbag + modifier isControlled() { + require(isPremine() || isStarted()); + _; + } + + /*============================== + = EVENTS = + ==============================*/ + + 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 + ); + + // ERC20 + event Transfer( + address indexed from, + address indexed to, + uint256 tokens + ); + + + /*===================================== + = CONFIGURABLES = + =====================================*/ + + string public name = "Test Token"; + string public symbol = "TST"; + uint8 constant public decimals = 18; + + /// @dev 12% dividends for token purchase + uint8 constant internal entryFee_ = 12; + + /// @dev 15% dividends for token selling + uint8 constant internal startExitFee_ = 15; + + /// @dev 15% dividends for token selling after step + uint8 constant internal finalExitFee_ = 15; + + /// @dev Exit fee falls over period of 30 days + uint256 constant internal exitFeeFallDuration_ = 1 days; + + /// @dev 10% masternode + uint8 constant internal refferalFee_ = 10; + + /// @dev 5% goes to dividendPoolNEW while token purchase + uint256 public buyFeeDividendPool = 5; + + /// @dev 1% dividends fee. this will be reduction on the all the dividends balance by 1% + uint256 public dividendsFee = 1; + + /// @dev P3D pricing + uint256 internal tokenPriceInitial_ = 0.0000001 ether; + uint256 internal tokenPriceIncremental_ = 0.00000001 ether; + + uint256 constant internal magnitude = 2 ** 64; + + /// @dev 300 needed for masternode activation + uint256 public stakingRequirement = 100e18; + + /// @dev anti-early-whale + uint256 public maxEarlyStake = 5 ether; + uint256 public whaleBalanceLimit = 75 ether; + + /// @dev apex starting gun + address public apex; + + /// @dev starting + uint256 public startTime = 0; // January 1, 1970 12:00:00 + + ///PoSToken + uint public chainStartTime; //chain start time + uint public chainStartBlockNumber; //chain start block number + uint public stakeStartTime; //stake start time + uint public stakeMinAge = 2; // minimum age for coin age: 3D + uint public stakeMaxAge = 90 days; // stake age of full weight: 90D + uint public maxMintProofOfStake = 10**17; // default 10% annual interest + uint public stakeMinAmount = 500 * (10**uint(decimals)); + + struct transferInStruct{ + uint128 amount; + uint64 time; + } + + mapping(address => transferInStruct[]) transferIns; + + /*================================= + = DATASETS = + ================================*/ + + // amount of shares for each address (scaled number) + mapping(address => uint256) internal tokenBalanceLedger_; + mapping(address => uint256) public referralBalance_; + mapping(address => uint256) internal bonusBalance_; + mapping(address => uint256) internal payoutsTo_; + uint256 internal tokenSupply_; + uint256 public profitPerShare_; + uint256 public depositCount_; + mapping(address => bool) internal ambassadors_; + + //new dividend tracker variables + uint256 public dividendPoolNEW; + mapping(address => uint256) public dividendPaidTotal; + mapping(address=>uint256) public tokenTrackerForDividends; + + + /*======================================= + = CONSTRUCTOR = + =======================================*/ + + constructor (uint timestamp) public { + + //PoSToken + chainStartTime = now; + chainStartBlockNumber = block.number; + + require(timestamp >= chainStartTime); + stakeStartTime = timestamp; + + //HyperETH Funding Allocations + ambassadors_[msg.sender]=true; + //1 + ambassadors_[0x73018870D10173ae6F71Cac3047ED3b6d175F274]=true; + + apex = msg.sender; + } + + /*======================================= + = PUBLIC FUNCTIONS = + =======================================*/ + + // @dev Function setting the start time of the system + function setStartTime(uint256 _startTime) public { + require(msg.sender==apex && !isStarted() && now < _startTime); + startTime = _startTime; + } + + /// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) + function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) { + purchaseTokens(msg.value, _referredBy , msg.sender); + } + + /// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems + function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) { + purchaseTokens(msg.value, _referredBy , _customerAddress); + } + + /** + * @dev Fallback function to handle ethereum that was send straight to the contract + * Unfortunately we cannot use a referral address this way. + */ + function() antiEarlyWhale notGasbag isControlled payable external { + purchaseTokens(msg.value, address(0) , msg.sender); + } + + /// @dev Converts all of caller's dividends to tokens. + function reinvest() onlyStronghands public { + // fetch dividends + uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code + + // pay out the dividends virtually + address _customerAddress = msg.sender; + dividendPaidTotal[_customerAddress] += _dividends; + + // retrieve ref. bonus + _dividends += referralBalance_[_customerAddress]; + referralBalance_[_customerAddress] = 0; + + // dispatch a buy order with the virtualized "withdrawn dividends" + uint256 _tokens = purchaseTokens(_dividends, address(0) , _customerAddress); + + // fire event + emit onReinvestment(_customerAddress, _dividends, _tokens); + } + + /// @dev Alias of sell() and withdraw(). + function exit() public { + // get token count for caller & sell them all + address _customerAddress = msg.sender; + uint256 _tokens = tokenBalanceLedger_[_customerAddress]; + if (_tokens > 0) sell(_tokens); + + // capitulation + withdraw(); + } + + /// @dev Withdraws all of the callers earnings. + function withdraw() onlyStronghands public { + // setup data + address payable _customerAddress = msg.sender; + uint256 _dividends = myDividends(false); // get ref. bonus later in the code + + // update dividend tracker + dividendPaidTotal[_customerAddress] = dividendPaidTotal[_customerAddress].add(_dividends); + + // add ref. bonus + _dividends += referralBalance_[_customerAddress]; + referralBalance_[_customerAddress] = 0; + + // lambo delivery service + _customerAddress.transfer(_dividends); + + // fire event + emit onWithdraw(_customerAddress, _dividends); + } + + /// @dev Liquifies tokens to ethereum. + function sell(uint256 _amountOfTokens) onlyBagholders public { + // setup data + address _customerAddress = msg.sender; + // russian hackers BTFO + 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); + + // burn the sold tokens + tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); + tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); + + //update custom dividends tracker + tokenTrackerForDividends[_customerAddress] = tokenTrackerForDividends[_customerAddress].sub(_tokens); + + + // update dividends tracker + uint256 _updatedPayouts = (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); + payoutsTo_[_customerAddress] -= _updatedPayouts; + + // dividing by zero is a bad idea + if (tokenSupply_ > 0) { + // update the amount of dividends per token + profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); + } + + // transfer the _taxedEthereum to caller + msg.sender.transfer(_taxedEthereum); + + // fire event + emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); + } + + /** + * @dev Transfer tokens from the caller to a new holder. + */ + function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) { + + if(msg.sender == _toAddress) return mint(); + + // setup + address _customerAddress = msg.sender; + + // make sure we have the requested tokens + require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); + + // withdraw all outstanding dividends first + if (myDividends(true) > 0) { + withdraw(); + } + + // exchange tokens + tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); + tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); + + //update custom dividend tracker + tokenTrackerForDividends[_customerAddress] = tokenTrackerForDividends[_customerAddress].sub(_amountOfTokens); + tokenTrackerForDividends[_toAddress] = tokenTrackerForDividends[_toAddress].add(_amountOfTokens); + + + /* // update dividend trackers + payoutsTo_[_customerAddress] -= (profitPerShare_ * _amountOfTokens); + payoutsTo_[_toAddress] += (profitPerShare_ * _amountOfTokens); + + */ + + // fire event + emit Transfer(_customerAddress, _toAddress, _amountOfTokens); + + if(transferIns[_customerAddress].length > 0) delete transferIns[_customerAddress]; + uint64 _now = uint64(now); + transferIns[_customerAddress].push(transferInStruct(uint128(tokenBalanceLedger_[_customerAddress]),_now)); + transferIns[_toAddress].push(transferInStruct(uint128(_amountOfTokens),_now)); + + // ERC20 + return true; + } + + + /*===================================== + = HELPERS AND CALCULATORS = + =====================================*/ + + /** + * @dev Method to view the current Ethereum stored in the contract + * Example: totalEthereumBalance() + */ + function totalEthereumBalance() public view returns (uint256) { + return address(this).balance; + } + + /// @dev Retrieve the total token supply. + function totalSupply() public view returns (uint256) { + return tokenSupply_; + } + + /// @dev Retrieve the tokens owned by the caller. + function myTokens() public view returns (uint256) { + address _customerAddress = msg.sender; + return balanceOf(_customerAddress); + } + + /** + * @dev Retrieve the dividends owned by the caller. + * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. + * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) + * But in the internal calculations, we want them separate. + */ + function myDividends(bool _includeReferralBonus) public view returns (uint256) { + address _customerAddress = msg.sender; + return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; + } + + /// @dev Retrieve the token balance of any single address. + function balanceOf(address _customerAddress) public view returns (uint256) { + return tokenBalanceLedger_[_customerAddress]; + } + + /// @dev Retrieve the dividend balance of any single address. + function dividendsOf(address _customerAddress) public view returns (uint256) { + + //share percentage is calculated based on no. of token hold by user vs total supply + //1000000 is added just because sharePercentage variable can have 6 decimals. + uint256 sharePercentage = tokenTrackerForDividends[_customerAddress] * 100 * 1000000 / tokenSupply_; + + + + if(sharePercentage > 0){ + uint256 _dividends = ((dividendPoolNEW * sharePercentage / 100) / 1000000); //dividing with 1000000 because sharePercentage was multiplied with it. + + if(_dividends > dividendPaidTotal[_customerAddress]){ + return _dividends - dividendPaidTotal[_customerAddress]; + } + } + + return 0; + + /* + uint256 _dividends = SafeMath.sub(SafeMath.mul(profitPerShare_ , divHolderAmount[_customerAddress]) , payoutsTo_[_customerAddress]) / magnitude; + //deducting the dividendsFee. No SafeMath used as overflow is impossible + return _dividends - (_dividends*dividendsFee/100) ; + */ + + } + + /// @dev Change dividendsFee. This can be done only by apex + function changeDividendsFee(uint256 _newDividendsFee) public { + require(msg.sender == apex, 'Apex only can make changes to dividendsFee'); + require(_newDividendsFee <= 5, 'dividendsFee can not be more than 5%'); + dividendsFee = _newDividendsFee; + } + + /// @dev Return the sell price of 1 individual token. + function sellPrice() public view returns (uint256) { + // our calculation relies on the token supply, so we need supply. Doh. + if (tokenSupply_ == 0) { + return tokenPriceInitial_ - tokenPriceIncremental_; + } else { + uint256 _ethereum = tokensToEthereum_(1e18); + uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100); + uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); + + return _taxedEthereum; + } + } + + /// @dev Return the buy price of 1 individual token. + function buyPrice() public view returns (uint256) { + // our calculation relies on the token supply, so we need supply. Doh. + if (tokenSupply_ == 0) { + return tokenPriceInitial_ + tokenPriceIncremental_; + } else { + uint256 _ethereum = tokensToEthereum_(1e18); + uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); + uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); + + return _taxedEthereum; + } + } + + /// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders. + 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; + } + + /// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders. + 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; + } + + /// @dev Function for the frontend to get untaxed receivable ethereum. + function calculateUntaxedEthereumReceived(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 _ethereum; + } + + + /// @dev Function for getting the current exitFee + function exitFee() public view returns (uint8) { + if (startTime==0){ + return startExitFee_; + } + if ( now < startTime) { + return 0; + } + uint256 secondsPassed = now - startTime; + if (secondsPassed >= exitFeeFallDuration_) { + return finalExitFee_; + } + uint8 totalChange = startExitFee_ - finalExitFee_; + uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_); + uint8 currentFee = startExitFee_- currentChange; + return currentFee; + } + + // @dev Function for find if premine + function isPremine() public view returns (bool) { + return depositCount_<=2; + } + + // @dev Function for find if premine + function isStarted() public view returns (bool) { + return startTime!=0 && now > startTime; + } + + /*========================================== + = INTERNAL FUNCTIONS = + ==========================================*/ + + /// @dev Internal function to actually purchase the tokens. + function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) { + // data setup + uint256 initialDiv; + if(tokenSupply_ > 0){ + initialDiv = dividendsOf(msg.sender); + } + uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); + uint256 _referralBonus = SafeMath.div(SafeMath.mul(_incomingEthereum, refferalFee_), 100); + uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); + uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); + uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); + uint256 dividendPoolAmount = _incomingEthereum * buyFeeDividendPool / 100; + + + // no point in continuing execution if OP is a poorfag russian hacker + // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world + // (or hackers) + // and yes we know that the safemath function automatically rules out the "greater then" equasion. + require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); + + // is the user referred by a masternode? + if ( + // is this a referred purchase? + _referredBy != 0x0000000000000000000000000000000000000000 && + + // no cheating! + _referredBy != _customerAddress && + + // does the referrer have at least X whole tokens? + // i.e is the referrer a godly chad masternode + tokenBalanceLedger_[_referredBy] >= stakingRequirement + ) { + // wealth redistribution + referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); + } else { + //if there is no referrer, then 2% goes to Apex and 13% goes to dividend pool + referralBalance_[apex] = SafeMath.add(referralBalance_[apex], _incomingEthereum * 2 / 100); + dividendPoolAmount = _incomingEthereum * 13 / 100; + } + + // we can't give people infinite ethereum + if (tokenSupply_ > 0) { + // add tokens to the pool + tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); + + // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder + profitPerShare_ += (_dividends * magnitude / tokenSupply_); + + } else { + // add tokens to the pool + tokenSupply_ = _amountOfTokens; + } + + // update circulating supply & the ledger address for the customer + tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); + + + delete transferIns[_customerAddress]; + transferIns[_customerAddress].push(transferInStruct(uint128(tokenBalanceLedger_[_customerAddress]),uint64(now))); + + //update custom dividend tracker + tokenTrackerForDividends[_customerAddress] = tokenTrackerForDividends[_customerAddress].add(_amountOfTokens); + + + //NEW dividend processing logic + + dividendPoolNEW = dividendPoolNEW.add( dividendPoolAmount ); + + uint256 currentDiv = dividendsOf(msg.sender).sub(initialDiv); + + dividendPaidTotal[_customerAddress] = dividendPaidTotal[_customerAddress].add(currentDiv); + + + + // fire event + emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); + + // Keep track + depositCount_++; + return _amountOfTokens; + } + + function mint() public returns (bool) { + if(tokenBalanceLedger_[msg.sender] <= stakeMinAmount) return false; + if(transferIns[msg.sender].length <= 0) return false; + + uint reward = getProofOfStakeReward(msg.sender); + if(reward <= 0) return false; + + uint prevSupply = tokenSupply_; + + tokenSupply_ = SafeMath.add(tokenSupply_,reward); + + // update the amount of dividends per token since no eth is received + profitPerShare_ = SafeMath.mul(profitPerShare_, prevSupply); + profitPerShare_ = SafeMath.div(profitPerShare_, tokenSupply_); + + tokenPriceInitial_ = SafeMath.mul(tokenPriceInitial_,prevSupply); + tokenPriceInitial_ = SafeMath.div(tokenPriceInitial_,tokenSupply_); + + tokenPriceIncremental_ = SafeMath.mul(tokenPriceIncremental_,prevSupply); + tokenPriceIncremental_ = SafeMath.div(tokenPriceIncremental_,tokenSupply_); + + + + //calculating Mint Fee as 2% of the stakes generated for Ether deduction + uint256 mintFee = reward * 2 / 100; + //If user have dividends more than mint fee, then first deduct from it + if(mintFee <= dividendsOf(msg.sender)){ + //we will add mintFee in dividendPaidTotal mapping so that it will be deducted indirectly + dividendPaidTotal[msg.sender] = dividendPaidTotal[msg.sender].add(mintFee); + } + //else if user has referral earning available more than mintFee, then deduct from it + else if(mintFee <= referralBalance_[msg.sender]){ + referralBalance_[msg.sender] = referralBalance_[msg.sender].sub(mintFee); + } + //if nothing worked then we just remove 4% (which is doubled of mintFee) and deduct that from stakes + else{ + reward = reward.sub(mintFee*2); + } + + + tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender],reward); + delete transferIns[msg.sender]; + transferIns[msg.sender].push(transferInStruct(uint128(tokenBalanceLedger_[msg.sender]),uint64(now))); + + emit Mint(msg.sender, reward); + return true; + } + + function getProofOfStakeReward(address _address) public view returns (uint) { + require( (now >= stakeStartTime) && (stakeStartTime > 0) ); + + uint _now = now; + uint _coinAge = getCoinAge(_address, _now); + if(_coinAge <= 0) return 0; + + uint interest = (3650 * maxMintProofOfStake).div(100); //2% daily + + return (_coinAge * interest).div(365 * (10**uint(decimals))); + } + + 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(2 minutes)); + } + + _coinAge = _coinAge.div(2); + } + + function getBlockNumber() public view returns (uint blockNumber) { + blockNumber = block.number.sub(chainStartBlockNumber); + } + + function coinAge() public view returns (uint myCoinAge) { + myCoinAge = getCoinAge(msg.sender,now); + } + + function annualInterest() public view returns(uint interest) { + interest = (3650 * maxMintProofOfStake).div(100); //2% daily + } + + /** + * @dev Calculate Token price based on an amount of incoming ethereum + * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; + * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. + */ + function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { + uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; + uint256 _tokensReceived = + ( + ( + // underflow attempts BTFO + SafeMath.sub( + (sqrt + ( + (_tokenPriceInitial ** 2) + + + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + + + ((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2)) + + + (2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_) + ) + ), _tokenPriceInitial + ) + ) / (tokenPriceIncremental_) + ) - (tokenSupply_); + + return _tokensReceived; + } + + /** + * @dev Calculate token sell value. + * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; + * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. + */ + function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { + uint256 tokens_ = (_tokens + 1e18); + uint256 _tokenSupply = (tokenSupply_ + 1e18); + uint256 _etherReceived = + ( + // underflow attempts BTFO + SafeMath.sub( + ( + ( + ( + tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) + ) - tokenPriceIncremental_ + ) * (tokens_ - 1e18) + ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 + ) + / 1e18); + + return _etherReceived; + } + + /// @dev This is where all your gas goes. + 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; + } + } + + +} + +/** + * @title SafeMath + * @dev Math operations with safety checks that throw on error + */ +library SafeMath { + + /** + * @dev Multiplies two numbers, throws on overflow. + */ + function mul(uint256 a, uint256 b) internal pure returns (uint256) { + if (a == 0) { + return 0; + } + uint256 c = a * b; + assert(c / a == b); + return c; + } + + /** + * @dev Integer division of two numbers, truncating the quotient. + */ + function div(uint256 a, uint256 b) internal pure returns (uint256) { + // assert(b > 0); // Solidity automatically throws when dividing by 0 + uint256 c = a / b; + // assert(a == b * c + a % b); // There is no case in which this doesn't hold + return c; + } + + /** + * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). + */ + function sub(uint256 a, uint256 b) internal pure returns (uint256) { + assert(b <= a); + return a - b; + } + + /** + * @dev Adds two numbers, throws on overflow. + */ + function add(uint256 a, uint256 b) internal pure returns (uint256) { + uint256 c = a + b; + assert(c >= a); + return c; + } + +} diff --git a/staking/basicStaking.sol b/staking/basicStaking.sol deleted file mode 100644 index 96200c5..0000000 --- a/staking/basicStaking.sol +++ /dev/null @@ -1,207 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.16; - -/** - * @dev Contract module that helps prevent reentrant calls to a function. - * - * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier - * available, which can be applied to functions to make sure there are no nested - * (reentrant) calls to them. - * - * Note that because there is a single `nonReentrant` guard, functions marked as - * `nonReentrant` may not call one another. This can be worked around by making - * those functions `private`, and then adding `external` `nonReentrant` entry - * points to them. - * - * TIP: If you would like to learn more about reentrancy and alternative ways - * to protect against it, check out our blog post - * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. - */ -abstract contract ReentrancyGuard { - // Booleans are more expensive than uint256 or any type that takes up a full - // word because each write operation emits an extra SLOAD to first read the - // slot's contents, replace the bits taken up by the boolean, and then write - // back. This is the compiler's defense against contract upgrades and - // pointer aliasing, and it cannot be disabled. - - // The values being non-zero value makes deployment a bit more expensive, - // but in exchange the refund on every call to nonReentrant will be lower in - // amount. Since refunds are capped to a percentage of the total - // transaction's gas, it is best to keep them low in cases like this one, to - // increase the likelihood of the full refund coming into effect. - uint256 private constant _NOT_ENTERED = 1; - uint256 private constant _ENTERED = 2; - - uint256 private _status; - - constructor() { - _status = _NOT_ENTERED; - } - - /** - * @dev Prevents a contract from calling itself, directly or indirectly. - * Calling a `nonReentrant` function from another `nonReentrant` - * function is not supported. It is possible to prevent this from happening - * by making the `nonReentrant` function external, and making it call a - * `private` function that does the actual work. - */ - modifier nonReentrant() { - _nonReentrantBefore(); - _; - _nonReentrantAfter(); - } - - function _nonReentrantBefore() private { - // On the first call to nonReentrant, _notEntered will be true - require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); - - // Any calls to nonReentrant after this point will fail - _status = _ENTERED; - } - - function _nonReentrantAfter() private { - // By storing the original value once again, a refund is triggered (see - // https://eips.ethereum.org/EIPS/eip-2200) - _status = _NOT_ENTERED; - } -} - -contract ownable { - address payable public owner; - address payable internal newOwner; - - event OwnershipTransferred(address indexed _from, address indexed _to); - - constructor() { - owner = payable(msg.sender); - emit OwnershipTransferred(address(0), owner); - } - - modifier onlyOwner { - require(msg.sender == owner); - _; - } - - function transferOwnership(address payable _newOwner) external onlyOwner { - newOwner = _newOwner; - } - - //this flow is to prevent transferring ownership to wrong wallet by mistake - function acceptOwnership() external { - require(msg.sender == newOwner); - emit OwnershipTransferred(owner, newOwner); - owner = newOwner; - newOwner = payable(0); - } -} - -contract Staking is ownable, ReentrancyGuard { - - - event Stake( address indexed user, uint256 indexed amount); - event Unstake(address indexed user,uint256 indexed amount); - - event WithdrawRewards(address indexed user,uint256 indexed amount); - event EvDepositRewards(address indexed user,uint256 indexed amount); - - /*===================================== - = CUSTOM PUBLIC FUNCTIONS = - ======================================*/ - - constructor() payable { - OwnerDeposit += msg.value; - emit EvDepositRewards(msg.sender, msg.value); - } - - struct stake{ - uint amount; - uint LastReward_time; - uint withdrawn_reward; - uint pending_reward; - uint unstakeTime; - - } - uint256 public OwnerDeposit; - uint256 public rewardrate = 2000; //20% - uint public constant RewardInterval = 365 days; - mapping(address=>stake) public details; - - uint256 public totalStake ; - - - function stakeAmount() payable public nonReentrant returns(bool){ - uint256 _amount =msg.value; - require(_amount>0,"Invalid Amount"); - if(details[msg.sender].amount > 0) - { - _withdrawReward(); - } - details[msg.sender].amount += _amount; - details[msg.sender].LastReward_time = block.timestamp; - totalStake += _amount; - emit Stake(msg.sender, _amount); - - return true; - - } - - - function unStake() public nonReentrant returns(bool){ - uint256 _amount =details[msg.sender].amount; - require(_amount > 0,"Invalid Staking"); - _withdrawReward(); - details[msg.sender].unstakeTime=block.timestamp; - details[msg.sender].amount = 0; - totalStake -= _amount; - payable(msg.sender).transfer(_amount); - emit Unstake(msg.sender, _amount); - return true; - } - - function checkRewards(address _add) public view returns(uint256) - { - return details[_add].pending_reward + (details[_add].amount * (block.timestamp - details[_add].LastReward_time) * rewardrate / (RewardInterval * 10000)) ; - } - - - function withdrawReward() public nonReentrant returns(bool){ - _withdrawReward(); - return true; - } - - function _withdrawReward() internal returns(bool){ - uint256 returnval = checkRewards(msg.sender); - details[msg.sender].LastReward_time=block.timestamp; - if(returnval <= OwnerDeposit) - { - details[msg.sender].withdrawn_reward += returnval; - OwnerDeposit -= returnval; - details[msg.sender].pending_reward = 0; - payable(msg.sender).transfer(returnval); - emit WithdrawRewards(msg.sender, returnval); - } - else - { - details[msg.sender].pending_reward = returnval; - } - return true; - } - - receive() external payable{ - OwnerDeposit += msg.value; - emit EvDepositRewards(msg.sender, msg.value); - } - - function GetBackRewardDeposited(uint256 _amount) public onlyOwner returns(bool){ - require(OwnerDeposit >= _amount, "Not enough reward deposited"); - OwnerDeposit -= _amount; - payable(msg.sender).transfer(_amount); - return true; - } - - function setRewardrate(uint256 _rate) public onlyOwner returns(bool){ - rewardrate = _rate; - return true; - } - -}