X
stringlengths
111
713k
y
stringclasses
56 values
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /// @title Interface for contracts conforming to ERC-721: Deed Standard /// @author William Entriken (https://phor.net), et al. /// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT) interface ERC721 { // COMPLIANCE WITH ERC-165 (DRAFT) ///////////////////////////////////////// /// @dev ERC-165 (draft) interface signature for itself // bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 // bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 // bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b // bytes4(keccak256('ownerOf(uint256)')) ^ // bytes4(keccak256('countOfDeeds()')) ^ // bytes4(keccak256('countOfDeedsByOwner(address)')) ^ // bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ // bytes4(keccak256('approve(address,uint256)')) ^ // bytes4(keccak256('takeOwnership(uint256)')); /// @notice Query a contract to see if it supports a certain interface /// @dev Returns `true` the interface is supported and `false` otherwise, /// returns `true` for INTERFACE_SIGNATURE_ERC165 and /// INTERFACE_SIGNATURE_ERC721, see ERC-165 for other interface signatures. function supportsInterface(bytes4 _interfaceID) external pure returns (bool); // PUBLIC QUERY FUNCTIONS ////////////////////////////////////////////////// /// @notice Find the owner of a deed /// @param _deedId The identifier for a deed we are inspecting /// @dev Deeds assigned to zero address are considered destroyed, and /// queries about them do throw. /// @return The non-zero address of the owner of deed `_deedId`, or `throw` /// if deed `_deedId` is not tracked by this contract function ownerOf(uint256 _deedId) external view returns (address _owner); /// @notice Count deeds tracked by this contract /// @return A count of the deeds tracked by this contract, where each one of /// them has an assigned and queryable owner function countOfDeeds() public view returns (uint256 _count); /// @notice Count all deeds assigned to an owner /// @dev Throws if `_owner` is the zero address, representing destroyed deeds. /// @param _owner An address where we are interested in deeds owned by them /// @return The number of deeds owned by `_owner`, possibly zero function countOfDeedsByOwner(address _owner) public view returns (uint256 _count); /// @notice Enumerate deeds assigned to an owner /// @dev Throws if `_index` >= `countOfDeedsByOwner(_owner)` or if /// `_owner` is the zero address, representing destroyed deeds. /// @param _owner An address where we are interested in deeds owned by them /// @param _index A counter between zero and `countOfDeedsByOwner(_owner)`, /// inclusive /// @return The identifier for the `_index`th deed assigned to `_owner`, /// (sort order not specified) function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId); // TRANSFER MECHANISM ////////////////////////////////////////////////////// /// @dev This event emits when ownership of any deed changes by any /// mechanism. This event emits when deeds are created (`from` == 0) and /// destroyed (`to` == 0). Exception: during contract creation, any /// transfers may occur without emitting `Transfer`. event Transfer(address indexed from, address indexed to, uint256 indexed deedId); /// @dev This event emits on any successful call to /// `approve(address _spender, uint256 _deedId)`. Exception: does not emit /// if an owner revokes approval (`_to` == 0x0) on a deed with no existing /// approval. event Approval(address indexed owner, address indexed approved, uint256 indexed deedId); /// @notice Approve a new owner to take your deed, or revoke approval by /// setting the zero address. You may `approve` any number of times while /// the deed is assigned to you, only the most recent approval matters. /// @dev Throws if `msg.sender` does not own deed `_deedId` or if `_to` == /// `msg.sender`. /// @param _deedId The deed you are granting ownership of function approve(address _to, uint256 _deedId) external; /// @notice Become owner of a deed for which you are currently approved /// @dev Throws if `msg.sender` is not approved to become the owner of /// `deedId` or if `msg.sender` currently owns `_deedId`. /// @param _deedId The deed that is being transferred function takeOwnership(uint256 _deedId) external; // SPEC EXTENSIONS ///////////////////////////////////////////////////////// /// @notice Transfer a deed to a new owner. /// @dev Throws if `msg.sender` does not own deed `_deedId` or if /// `_to` == 0x0. /// @param _to The address of the new owner. /// @param _deedId The deed you are transferring. function transfer(address _to, uint256 _deedId) external; } /// @title Metadata extension to ERC-721 interface /// @author William Entriken (https://phor.net) /// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT) interface ERC721Metadata { /// @dev ERC-165 (draft) interface signature for ERC721 // bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 // bytes4(keccak256('name()')) ^ // bytes4(keccak256('symbol()')) ^ // bytes4(keccak256('deedUri(uint256)')); /// @notice A descriptive name for a collection of deeds managed by this /// contract /// @dev Wallets and exchanges MAY display this to the end user. function name() public pure returns (string _deedName); /// @notice An abbreviated name for deeds managed by this contract /// @dev Wallets and exchanges MAY display this to the end user. function symbol() public pure returns (string _deedSymbol); /// @notice A distinct URI (RFC 3986) for a given token. /// @dev If: /// * The URI is a URL /// * The URL is accessible /// * The URL points to a valid JSON file format (ECMA-404 2nd ed.) /// * The JSON base element is an object /// then these names of the base element SHALL have special meaning: /// * "name": A string identifying the item to which `_deedId` grants /// ownership /// * "description": A string detailing the item to which `_deedId` grants /// ownership /// * "image": A URI pointing to a file of image/* mime type representing /// the item to which `_deedId` grants ownership /// Wallets and exchanges MAY display this to the end user. /// Consider making any images at a width between 320 and 1080 pixels and /// aspect ratio between 1.91:1 and 4:5 inclusive. function deedUri(uint256 _deedId) external pure returns (string _uri); } /// @dev Implements access control to the DWorld contract. contract DWorldAccessControl is Claimable, Pausable, CanReclaimToken { address public cfoAddress; function DWorldAccessControl() public { // The creator of the contract is the initial CFO. cfoAddress = msg.sender; } /// @dev Access modifier for CFO-only functionality. modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Assigns a new address to act as the CFO. Only available to the current contract owner. /// @param _newCFO The address of the new CFO. function setCFO(address _newCFO) external onlyOwner { require(_newCFO != address(0)); cfoAddress = _newCFO; } } /// @dev Defines base data structures for DWorld. contract DWorldBase is DWorldAccessControl { using SafeMath for uint256; /// @dev All minted plots (array of plot identifiers). There are /// 2^16 * 2^16 possible plots (covering the entire world), thus /// 32 bits are required. This fits in a uint32. Storing /// the identifiers as uint32 instead of uint256 makes storage /// cheaper. (The impact of this in mappings is less noticeable, /// and using uint32 in the mappings below actually *increases* /// gas cost for minting). uint32[] public plots; mapping (uint256 => address) identifierToOwner; mapping (uint256 => address) identifierToApproved; mapping (address => uint256) ownershipDeedCount; // Boolean indicating whether the plot was bought before the migration. mapping (uint256 => bool) public identifierIsOriginal; /// @dev Event fired when a plot's data are changed. The plot /// data are not stored in the contract directly, instead the /// data are logged to the block. This gives significant /// reductions in gas requirements (~75k for minting with data /// instead of ~180k). However, it also means plot data are /// not available from *within* other contracts. event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl); /// @notice Get all minted plots. function getAllPlots() external view returns(uint32[]) { return plots; } /// @dev Represent a 2D coordinate as a single uint. /// @param x The x-coordinate. /// @param y The y-coordinate. function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) { require(validCoordinate(x, y)); return (y << 16) + x; } /// @dev Turn a single uint representation of a coordinate into its x and y parts. /// @param identifier The uint representation of a coordinate. function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) { require(validIdentifier(identifier)); y = identifier >> 16; x = identifier - (y << 16); } /// @dev Test whether the coordinate is valid. /// @param x The x-part of the coordinate to test. /// @param y The y-part of the coordinate to test. function validCoordinate(uint256 x, uint256 y) public pure returns(bool) { return x < 65536 && y < 65536; // 2^16 } /// @dev Test whether an identifier is valid. /// @param identifier The identifier to test. function validIdentifier(uint256 identifier) public pure returns(bool) { return identifier < 4294967296; // 2^16 * 2^16 } /// @dev Set a plot's data. /// @param identifier The identifier of the plot to set data for. function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal { SetData(identifier, name, description, imageUrl, infoUrl); } } /// @dev Holds deed functionality such as approving and transferring. Implements ERC721. contract DWorldDeed is DWorldBase, ERC721, ERC721Metadata { /// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function name() public pure returns (string _deedName) { _deedName = "DWorld Plots"; } /// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "DWP"; } /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('countOfDeeds()')) ^ bytes4(keccak256('countOfDeedsByOwner(address)')) ^ bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('deedUri(uint256)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. /// (ERC-165 and ERC-721.) function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return ( (_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721) || (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata) ); } /// @dev Checks if a given address owns a particular plot. /// @param _owner The address of the owner to check for. /// @param _deedId The plot identifier to check for. function _owns(address _owner, uint256 _deedId) internal view returns (bool) { return identifierToOwner[_deedId] == _owner; } /// @dev Approve a given address to take ownership of a deed. /// @param _from The address approving taking ownership. /// @param _to The address to approve taking ownership. /// @param _deedId The identifier of the deed to give approval for. function _approve(address _from, address _to, uint256 _deedId) internal { identifierToApproved[_deedId] = _to; // Emit event. Approval(_from, _to, _deedId); } /// @dev Checks if a given address has approval to take ownership of a deed. /// @param _claimant The address of the claimant to check for. /// @param _deedId The identifier of the deed to check for. function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) { return identifierToApproved[_deedId] == _claimant; } /// @dev Assigns ownership of a specific deed to an address. /// @param _from The address to transfer the deed from. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed to transfer. function _transfer(address _from, address _to, uint256 _deedId) internal { // The number of plots is capped at 2^16 * 2^16, so this cannot // be overflowed. ownershipDeedCount[_to]++; // Transfer ownership. identifierToOwner[_deedId] = _to; // When a new deed is minted, the _from address is 0x0, but we // do not track deed ownership of 0x0. if (_from != address(0)) { ownershipDeedCount[_from]--; // Clear taking ownership approval. delete identifierToApproved[_deedId]; } // Emit the transfer event. Transfer(_from, _to, _deedId); } // ERC 721 implementation /// @notice Returns the total number of deeds currently in existence. /// @dev Required for ERC-721 compliance. function countOfDeeds() public view returns (uint256) { return plots.length; } /// @notice Returns the number of deeds owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function countOfDeedsByOwner(address _owner) public view returns (uint256) { return ownershipDeedCount[_owner]; } /// @notice Returns the address currently assigned ownership of a given deed. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _deedId) external view returns (address _owner) { _owner = identifierToOwner[_deedId]; require(_owner != address(0)); } /// @notice Approve a given address to take ownership of a deed. /// @param _to The address to approve taking owernship. /// @param _deedId The identifier of the deed to give approval for. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; approveMultiple(_to, _deedIds); } /// @notice Approve a given address to take ownership of multiple deeds. /// @param _to The address to approve taking ownership. /// @param _deedIds The identifiers of the deeds to give approval for. function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Ensure the sender is not approving themselves. require(msg.sender != _to); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // Require the sender is the owner of the deed. require(_owns(msg.sender, _deedId)); // Perform the approval. _approve(msg.sender, _to, _deedId); } } /// @notice Transfer a deed to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your /// deed may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedId The identifier of the deed to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; transferMultiple(_to, _deedIds); } /// @notice Transfers multiple deeds to another address. If transferring to /// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721, /// or your deeds may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedIds The identifiers of the deeds to transfer. function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // One can only transfer their own plots. require(_owns(msg.sender, _deedId)); // Transfer ownership _transfer(msg.sender, _to, _deedId); } } /// @notice Transfer a deed owned by another address, for which the calling /// address has previously been granted transfer approval by the owner. /// @param _deedId The identifier of the deed to be transferred. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; takeOwnershipMultiple(_deedIds); } /// @notice Transfer multiple deeds owned by another address, for which the /// calling address has previously been granted transfer approval by the owner. /// @param _deedIds The identifier of the deed to be transferred. function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; address _from = identifierToOwner[_deedId]; // Check for transfer approval require(_approvedFor(msg.sender, _deedId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, msg.sender, _deedId); } } /// @notice Returns a list of all deed identifiers assigned to an address. /// @param _owner The owner whose deeds we are interested in. /// @dev This method MUST NEVER be called by smart contract code. It's very /// expensive and is not supported in contract-to-contract calls as it returns /// a dynamic array (only supported for web3 calls). function deedsOfOwner(address _owner) external view returns(uint256[]) { uint256 deedCount = countOfDeedsByOwner(_owner); if (deedCount == 0) { // Return an empty array. return new uint256[](0); } else { uint256[] memory result = new uint256[](deedCount); uint256 totalDeeds = countOfDeeds(); uint256 resultIndex = 0; for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { result[resultIndex] = identifier; resultIndex++; } } return result; } } /// @notice Returns a deed identifier of the owner at the given index. /// @param _owner The address of the owner we want to get a deed for. /// @param _index The index of the deed we want. function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { // The index should be valid. require(_index < countOfDeedsByOwner(_owner)); // Loop through all plots, accounting the number of plots of the owner we've seen. uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; } seen++; } } } /// @notice Returns an (off-chain) metadata url for the given deed. /// @param _deedId The identifier of the deed to get the metadata /// url for. /// @dev Implementation of optional ERC-721 functionality. function deedUri(uint256 _deedId) external pure returns (string uri) { require(validIdentifier(_deedId)); var (x, y) = identifierToCoordinate(_deedId); // Maximum coordinate length in decimals is 5 (65535) uri = "https://dworld.io/plot/xxxxx/xxxxx"; bytes memory _uri = bytes(uri); for (uint256 i = 0; i < 5; i++) { _uri[27 - i] = byte(48 + (x / 10 ** i) % 10); _uri[33 - i] = byte(48 + (y / 10 ** i) % 10); } } } /// @dev Holds functionality for finance related to plots. contract DWorldFinance is DWorldDeed { /// Total amount of Ether yet to be paid to auction beneficiaries. uint256 public outstandingEther = 0 ether; /// Amount of Ether yet to be paid per beneficiary. mapping (address => uint256) public addressToEtherOwed; /// Base price for unclaimed plots. uint256 public unclaimedPlotPrice = 0.0125 ether; /// Dividend per plot surrounding a new claim, in 1/1000th of percentages /// of the base unclaimed plot price. uint256 public claimDividendPercentage = 50000; /// Percentage of the buyout price that goes towards dividends. uint256 public buyoutDividendPercentage = 5000; /// Buyout fee in 1/1000th of a percentage. uint256 public buyoutFeePercentage = 3500; /// Number of free claims per address. mapping (address => uint256) freeClaimAllowance; /// Initial price paid for a plot. mapping (uint256 => uint256) public initialPricePaid; /// Current plot price. mapping (uint256 => uint256) public identifierToBuyoutPrice; /// Boolean indicating whether the plot has been bought out at least once. mapping (uint256 => bool) identifierToBoughtOutOnce; /// @dev Event fired when dividend is paid for a new plot claim. event ClaimDividend(address indexed from, address indexed to, uint256 deedIdFrom, uint256 indexed deedIdTo, uint256 dividend); /// @dev Event fired when a buyout is performed. event Buyout(address indexed buyer, address indexed seller, uint256 indexed deedId, uint256 winnings, uint256 totalCost, uint256 newPrice); /// @dev Event fired when dividend is paid for a buyout. event BuyoutDividend(address indexed from, address indexed to, uint256 deedIdFrom, uint256 indexed deedIdTo, uint256 dividend); /// @dev Event fired when the buyout price is manually changed for a plot. event SetBuyoutPrice(uint256 indexed deedId, uint256 newPrice); /// @dev The time after which buyouts will be enabled. Set in the DWorldCore constructor. uint256 public buyoutsEnabledFromTimestamp; /// @notice Sets the new price for unclaimed plots. /// @param _unclaimedPlotPrice The new price for unclaimed plots. function setUnclaimedPlotPrice(uint256 _unclaimedPlotPrice) external onlyCFO { unclaimedPlotPrice = _unclaimedPlotPrice; } /// @notice Sets the new dividend percentage for unclaimed plots. /// @param _claimDividendPercentage The new dividend percentage for unclaimed plots. function setClaimDividendPercentage(uint256 _claimDividendPercentage) external onlyCFO { // Claim dividend percentage must be 10% at the least. // Claim dividend percentage may be 100% at the most. require(10000 <= _claimDividendPercentage && _claimDividendPercentage <= 100000); claimDividendPercentage = _claimDividendPercentage; } /// @notice Sets the new dividend percentage for buyouts. /// @param _buyoutDividendPercentage The new dividend percentage for buyouts. function setBuyoutDividendPercentage(uint256 _buyoutDividendPercentage) external onlyCFO { // Buyout dividend must be 2% at the least. // Buyout dividend percentage may be 12.5% at the most. require(2000 <= _buyoutDividendPercentage && _buyoutDividendPercentage <= 12500); buyoutDividendPercentage = _buyoutDividendPercentage; } /// @notice Sets the new fee percentage for buyouts. /// @param _buyoutFeePercentage The new fee percentage for buyouts. function setBuyoutFeePercentage(uint256 _buyoutFeePercentage) external onlyCFO { // Buyout fee may be 5% at the most. require(0 <= _buyoutFeePercentage && _buyoutFeePercentage <= 5000); buyoutFeePercentage = _buyoutFeePercentage; } /// @notice The claim dividend to be paid for each adjacent plot, and /// as a flat dividend for each buyout. function claimDividend() public view returns (uint256) { return unclaimedPlotPrice.mul(claimDividendPercentage).div(100000); } /// @notice Set the free claim allowance for an address. /// @param addr The address to set the free claim allowance for. /// @param allowance The free claim allowance to set. function setFreeClaimAllowance(address addr, uint256 allowance) external onlyCFO { freeClaimAllowance[addr] = allowance; } /// @notice Get the free claim allowance of an address. /// @param addr The address to get the free claim allowance of. function freeClaimAllowanceOf(address addr) external view returns (uint256) { return freeClaimAllowance[addr]; } /// @dev Assign balance to an account. /// @param addr The address to assign balance to. /// @param amount The amount to assign. function _assignBalance(address addr, uint256 amount) internal { addressToEtherOwed[addr] = addressToEtherOwed[addr].add(amount); outstandingEther = outstandingEther.add(amount); } /// @dev Find the _claimed_ plots surrounding a plot. /// @param _deedId The identifier of the plot to get the surrounding plots for. function _claimedSurroundingPlots(uint256 _deedId) internal view returns (uint256[] memory) { var (x, y) = identifierToCoordinate(_deedId); // Find all claimed surrounding plots. uint256 claimed = 0; // Create memory buffer capable of holding all plots. uint256[] memory _plots = new uint256[](8); // Loop through all neighbors. for (int256 dx = -1; dx <= 1; dx++) { for (int256 dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) { // Skip the center (i.e., the plot itself). continue; } // Get the coordinates of this neighboring identifier. uint256 neighborIdentifier = coordinateToIdentifier( uint256(int256(x) + dx) % 65536, uint256(int256(y) + dy) % 65536 ); if (identifierToOwner[neighborIdentifier] != 0x0) { _plots[claimed] = neighborIdentifier; claimed++; } } } // Memory arrays cannot be resized, so copy all // plots from the buffer to the plot array. uint256[] memory plots = new uint256[](claimed); for (uint256 i = 0; i < claimed; i++) { plots[i] = _plots[i]; } return plots; } /// @dev Assign claim dividend to an address. /// @param _from The address who paid the dividend. /// @param _to The dividend beneficiary. /// @param _deedIdFrom The identifier of the deed the dividend is being paid for. /// @param _deedIdTo The identifier of the deed the dividend is being paid to. function _assignClaimDividend(address _from, address _to, uint256 _deedIdFrom, uint256 _deedIdTo) internal { uint256 _claimDividend = claimDividend(); // Trigger event. ClaimDividend(_from, _to, _deedIdFrom, _deedIdTo, _claimDividend); // Assign the dividend. _assignBalance(_to, _claimDividend); } /// @dev Calculate and assign the dividend payable for the new plot claim. /// A new claim pays dividends to all existing surrounding plots. /// @param _deedId The identifier of the new plot to calculate and assign dividends for. /// Assumed to be valid. function _calculateAndAssignClaimDividends(uint256 _deedId) internal returns (uint256 totalClaimDividend) { // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // Keep track of the claim dividend. uint256 _claimDividend = claimDividend(); totalClaimDividend = 0; // Assign claim dividend. for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) { if (identifierToOwner[claimedSurroundingPlots[i]] != msg.sender) { totalClaimDividend = totalClaimDividend.add(_claimDividend); _assignClaimDividend(msg.sender, identifierToOwner[claimedSurroundingPlots[i]], _deedId, claimedSurroundingPlots[i]); } } } /// @dev Calculate the next buyout price given the current total buyout cost. /// @param totalCost The current total buyout cost. function nextBuyoutPrice(uint256 totalCost) public pure returns (uint256) { if (totalCost < 0.05 ether) { return totalCost * 2; } else if (totalCost < 0.2 ether) { return totalCost * 170 / 100; // * 1.7 } else if (totalCost < 0.5 ether) { return totalCost * 150 / 100; // * 1.5 } else { return totalCost.mul(125).div(100); // * 1.25 } } /// @notice Get the buyout cost for a given plot. /// @param _deedId The identifier of the plot to get the buyout cost for. function buyoutCost(uint256 _deedId) external view returns (uint256) { // The current buyout price. uint256 price = identifierToBuyoutPrice[_deedId]; // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // The total cost is the price plus flat rate dividends based on claim dividends. uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length); return price.add(flatDividends); } /// @dev Assign the proceeds of the buyout. /// @param _deedId The identifier of the plot that is being bought out. function _assignBuyoutProceeds( address currentOwner, uint256 _deedId, uint256[] memory claimedSurroundingPlots, uint256 currentOwnerWinnings, uint256 totalDividendPerBeneficiary, uint256 totalCost ) internal { // Calculate and assign the current owner's winnings. Buyout(msg.sender, currentOwner, _deedId, currentOwnerWinnings, totalCost, nextBuyoutPrice(totalCost)); _assignBalance(currentOwner, currentOwnerWinnings); // Assign dividends to owners of surrounding plots. for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) { address beneficiary = identifierToOwner[claimedSurroundingPlots[i]]; BuyoutDividend(msg.sender, beneficiary, _deedId, claimedSurroundingPlots[i], totalDividendPerBeneficiary); _assignBalance(beneficiary, totalDividendPerBeneficiary); } } /// @dev Calculate and assign the proceeds from the buyout. /// @param currentOwner The current owner of the plot that is being bought out. /// @param _deedId The identifier of the plot that is being bought out. /// @param claimedSurroundingPlots The surrounding plots that have been claimed. function _calculateAndAssignBuyoutProceeds(address currentOwner, uint256 _deedId, uint256[] memory claimedSurroundingPlots) internal returns (uint256 totalCost) { // The current price. uint256 price = identifierToBuyoutPrice[_deedId]; // The total cost is the price plus flat rate dividends based on claim dividends. uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length); totalCost = price.add(flatDividends); // Calculate the variable dividends based on the buyout price // (only to be paid if there are surrounding plots). uint256 variableDividends = price.mul(buyoutDividendPercentage).div(100000); // Calculate fees. uint256 fee = price.mul(buyoutFeePercentage).div(100000); // Calculate and assign buyout proceeds. uint256 currentOwnerWinnings = price.sub(fee); uint256 totalDividendPerBeneficiary; if (claimedSurroundingPlots.length > 0) { // If there are surrounding plots, variable dividend is to be paid // based on the buyout price.. currentOwnerWinnings = currentOwnerWinnings.sub(variableDividends); // Calculate the dividend per surrounding plot. totalDividendPerBeneficiary = flatDividends.add(variableDividends) / claimedSurroundingPlots.length; } _assignBuyoutProceeds( currentOwner, _deedId, claimedSurroundingPlots, currentOwnerWinnings, totalDividendPerBeneficiary, totalCost ); } /// @notice Buy the current owner out of the plot. function buyout(uint256 _deedId) external payable whenNotPaused { buyoutWithData(_deedId, "", "", "", ""); } /// @notice Buy the current owner out of the plot. function buyoutWithData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { // Buyouts must be enabled. require(buyoutsEnabledFromTimestamp <= block.timestamp); address currentOwner = identifierToOwner[_deedId]; // The plot must be owned before it can be bought out. require(currentOwner != 0x0); // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // Assign the buyout proceeds and retrieve the total cost. uint256 totalCost = _calculateAndAssignBuyoutProceeds(currentOwner, _deedId, claimedSurroundingPlots); // Ensure the message has enough value. require(msg.value >= totalCost); // Transfer the plot. _transfer(currentOwner, msg.sender, _deedId); // Set the plot data SetData(_deedId, name, description, imageUrl, infoUrl); // Calculate and set the new plot price. identifierToBuyoutPrice[_deedId] = nextBuyoutPrice(totalCost); // Indicate the plot has been bought out at least once if (!identifierToBoughtOutOnce[_deedId]) { identifierToBoughtOutOnce[_deedId] = true; } // Calculate the excess Ether sent. // msg.value is greater than or equal to totalCost, // so this cannot underflow. uint256 excess = msg.value - totalCost; if (excess > 0) { // Refund any excess Ether (not susceptible to re-entry attack, as // the owner is assigned before the transfer takes place). msg.sender.transfer(excess); } } /// @notice Calculate the maximum initial buyout price for a plot. /// @param _deedId The identifier of the plot to get the maximum initial buyout price for. function maximumInitialBuyoutPrice(uint256 _deedId) public view returns (uint256) { // The initial buyout price can be set to 4x the initial plot price // (or 100x for the original pre-migration plots). uint256 mul = 4; if (identifierIsOriginal[_deedId]) { mul = 100; } return initialPricePaid[_deedId].mul(mul); } /// @notice Test whether a buyout price is valid. /// @param _deedId The identifier of the plot to test the buyout price for. /// @param price The buyout price to test. function validInitialBuyoutPrice(uint256 _deedId, uint256 price) public view returns (bool) { return (price >= unclaimedPlotPrice && price <= maximumInitialBuyoutPrice(_deedId)); } /// @notice Manually set the initial buyout price of a plot. /// @param _deedId The identifier of the plot to set the buyout price for. /// @param price The value to set the buyout price to. function setInitialBuyoutPrice(uint256 _deedId, uint256 price) public whenNotPaused { // One can only set the buyout price of their own plots. require(_owns(msg.sender, _deedId)); // The initial buyout price can only be set if the plot has never been bought out before. require(!identifierToBoughtOutOnce[_deedId]); // The buyout price must be valid. require(validInitialBuyoutPrice(_deedId, price)); // Set the buyout price. identifierToBuyoutPrice[_deedId] = price; // Trigger the buyout price event. SetBuyoutPrice(_deedId, price); } } /// @dev Holds functionality for minting new plot deeds. contract DWorldMinting is DWorldFinance { /// @notice Buy an unclaimed plot. /// @param _deedId The unclaimed plot to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. function claimPlot(uint256 _deedId, uint256 _buyoutPrice) external payable whenNotPaused { claimPlotWithData(_deedId, _buyoutPrice, "", "", "", ""); } /// @notice Buy an unclaimed plot. /// @param _deedId The unclaimed plot to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. /// @param name The name to give the plot. /// @param description The description to add to the plot. /// @param imageUrl The image url for the plot. /// @param infoUrl The info url for the plot. function claimPlotWithData(uint256 _deedId, uint256 _buyoutPrice, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; claimPlotMultipleWithData(_deedIds, _buyoutPrice, name, description, imageUrl, infoUrl); } /// @notice Buy unclaimed plots. /// @param _deedIds The unclaimed plots to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. function claimPlotMultiple(uint256[] _deedIds, uint256 _buyoutPrice) external payable whenNotPaused { claimPlotMultipleWithData(_deedIds, _buyoutPrice, "", "", "", ""); } /// @notice Buy unclaimed plots. /// @param _deedIds The unclaimed plots to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. /// @param name The name to give the plots. /// @param description The description to add to the plots. /// @param imageUrl The image url for the plots. /// @param infoUrl The info url for the plots. function claimPlotMultipleWithData(uint256[] _deedIds, uint256 _buyoutPrice, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { uint256 buyAmount = _deedIds.length; uint256 etherRequired; if (freeClaimAllowance[msg.sender] > 0) { // The sender has a free claim allowance. if (freeClaimAllowance[msg.sender] > buyAmount) { // Subtract from allowance. freeClaimAllowance[msg.sender] -= buyAmount; // No ether is required. etherRequired = 0; } else { uint256 freeAmount = freeClaimAllowance[msg.sender]; // The full allowance has been used. delete freeClaimAllowance[msg.sender]; // The subtraction cannot underflow, as freeAmount <= buyAmount. etherRequired = unclaimedPlotPrice.mul(buyAmount - freeAmount); } } else { // The sender does not have a free claim allowance. etherRequired = unclaimedPlotPrice.mul(buyAmount); } uint256 offset = plots.length; // Allocate additional memory for the plots array // (this is more efficient than .push-ing each individual // plot, as that requires multiple dynamic allocations). plots.length = plots.length.add(_deedIds.length); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; require(validIdentifier(_deedId)); // The plot must be unowned (a plot deed cannot be transferred to // 0x0, so once a plot is claimed it will always be owned by a // non-zero address). require(identifierToOwner[_deedId] == address(0)); // Create the plot plots[offset + i] = uint32(_deedId); // Transfer the new plot to the sender. _transfer(address(0), msg.sender, _deedId); // Set the plot data. _setPlotData(_deedId, name, description, imageUrl, infoUrl); // Calculate and assign claim dividends. uint256 claimDividends = _calculateAndAssignClaimDividends(_deedId); etherRequired = etherRequired.add(claimDividends); // Set the initial price paid for the plot. initialPricePaid[_deedId] = unclaimedPlotPrice.add(claimDividends); // Set the initial buyout price. Throws if it does not succeed. setInitialBuyoutPrice(_deedId, _buyoutPrice); } // Ensure enough ether is supplied. require(msg.value >= etherRequired); // Calculate the excess ether sent // msg.value is greater than or equal to etherRequired, // so this cannot underflow. uint256 excess = msg.value - etherRequired; if (excess > 0) { // Refund any excess ether (not susceptible to re-entry attack, as // the owner is assigned before the transfer takes place). msg.sender.transfer(excess); } } } /// @title The internal clock auction functionality. /// Inspired by CryptoKitties' clock auction contract ClockAuctionBase { // Address of the ERC721 contract this auction is linked to. ERC721 public deedContract; // Fee per successful auction in 1/1000th of a percentage. uint256 public fee; // Total amount of ether yet to be paid to auction beneficiaries. uint256 public outstandingEther = 0 ether; // Amount of ether yet to be paid per beneficiary. mapping (address => uint256) public addressToEtherOwed; /// @dev Represents a deed auction. /// Care has been taken to ensure the auction fits in /// two 256-bit words. struct Auction { address seller; uint128 startPrice; uint128 endPrice; uint64 duration; uint64 startedAt; } mapping (uint256 => Auction) identifierToAuction; // Events event AuctionCreated(address indexed seller, uint256 indexed deedId, uint256 startPrice, uint256 endPrice, uint256 duration); event AuctionSuccessful(address indexed buyer, uint256 indexed deedId, uint256 totalPrice); event AuctionCancelled(uint256 indexed deedId); /// @dev Modifier to check whether the value can be stored in a 64 bit uint. modifier fitsIn64Bits(uint256 _value) { require (_value == uint256(uint64(_value))); _; } /// @dev Modifier to check whether the value can be stored in a 128 bit uint. modifier fitsIn128Bits(uint256 _value) { require (_value == uint256(uint128(_value))); _; } function ClockAuctionBase(address _deedContractAddress, uint256 _fee) public { deedContract = ERC721(_deedContractAddress); // Contract must indicate support for ERC721 through its interface signature. require(deedContract.supportsInterface(0xda671b9b)); // Fee must be between 0 and 100%. require(0 <= _fee && _fee <= 100000); fee = _fee; } /// @dev Checks whether the given auction is active. /// @param auction The auction to check for activity. function _activeAuction(Auction storage auction) internal view returns (bool) { return auction.startedAt > 0; } /// @dev Put the deed into escrow, thereby taking ownership of it. /// @param _deedId The identifier of the deed to place into escrow. function _escrow(uint256 _deedId) internal { // Throws if the transfer fails deedContract.takeOwnership(_deedId); } /// @dev Create the auction. /// @param _deedId The identifier of the deed to create the auction for. /// @param auction The auction to create. function _createAuction(uint256 _deedId, Auction auction) internal { // Add the auction to the auction mapping. identifierToAuction[_deedId] = auction; // Trigger auction created event. AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration); } /// @dev Bid on an auction. /// @param _buyer The address of the buyer. /// @param _value The value sent by the sender (in ether). /// @param _deedId The identifier of the deed to bid on. function _bid(address _buyer, uint256 _value, uint256 _deedId) internal { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); // Calculate the auction's current price. uint256 price = _currentPrice(auction); // Make sure enough funds were sent. require(_value >= price); address seller = auction.seller; if (price > 0) { uint256 totalFee = _calculateFee(price); uint256 proceeds = price - totalFee; // Assign the proceeds to the seller. // We do not send the proceeds directly, as to prevent // malicious sellers from denying auctions (and burning // the buyer's gas). _assignProceeds(seller, proceeds); } AuctionSuccessful(_buyer, _deedId, price); // The bid was won! _winBid(seller, _buyer, _deedId, price); // Remove the auction (we do this at the end, as // winBid might require some additional information // that will be removed when _removeAuction is // called. As we do not transfer funds here, we do // not have to worry about re-entry attacks. _removeAuction(_deedId); } /// @dev Perform the bid win logic (in this case: transfer the deed). /// @param _seller The address of the seller. /// @param _winner The address of the winner. /// @param _deedId The identifier of the deed. /// @param _price The price the auction was bought at. function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal { _transfer(_winner, _deedId); } /// @dev Cancel an auction. /// @param _deedId The identifier of the deed for which the auction should be cancelled. /// @param auction The auction to cancel. function _cancelAuction(uint256 _deedId, Auction auction) internal { // Remove the auction _removeAuction(_deedId); // Transfer the deed back to the seller _transfer(auction.seller, _deedId); // Trigger auction cancelled event. AuctionCancelled(_deedId); } /// @dev Remove an auction. /// @param _deedId The identifier of the deed for which the auction should be removed. function _removeAuction(uint256 _deedId) internal { delete identifierToAuction[_deedId]; } /// @dev Transfer a deed owned by this contract to another address. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed. function _transfer(address _to, uint256 _deedId) internal { // Throws if the transfer fails deedContract.transfer(_to, _deedId); } /// @dev Assign proceeds to an address. /// @param _to The address to assign proceeds to. /// @param _value The proceeds to assign. function _assignProceeds(address _to, uint256 _value) internal { outstandingEther += _value; addressToEtherOwed[_to] += _value; } /// @dev Calculate the current price of an auction. function _currentPrice(Auction storage _auction) internal view returns (uint256) { require(now >= _auction.startedAt); uint256 secondsPassed = now - _auction.startedAt; if (secondsPassed >= _auction.duration) { return _auction.endPrice; } else { // Negative if the end price is higher than the start price! int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice); // Calculate the current price based on the total change over the entire // auction duration, and the amount of time passed since the start of the // auction. int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration); // Calculate the final price. Note this once again // is representable by a uint256, as the price can // never be negative. int256 price = int256(_auction.startPrice) + currentPriceChange; // This never throws. assert(price >= 0); return uint256(price); } } /// @dev Calculate the fee for a given price. /// @param _price The price to calculate the fee for. function _calculateFee(uint256 _price) internal view returns (uint256) { // _price is guaranteed to fit in a uint128 due to the createAuction entry // modifiers, so this cannot overflow. return _price * fee / 100000; } } contract ClockAuction is ClockAuctionBase, Pausable { function ClockAuction(address _deedContractAddress, uint256 _fee) ClockAuctionBase(_deedContractAddress, _fee) public {} /// @notice Update the auction fee. /// @param _fee The new fee. function setFee(uint256 _fee) external onlyOwner { require(0 <= _fee && _fee <= 100000); fee = _fee; } /// @notice Get the auction for the given deed. /// @param _deedId The identifier of the deed to get the auction for. /// @dev Throws if there is no auction for the given deed. function getAuction(uint256 _deedId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active require(_activeAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt ); } /// @notice Create an auction for a given deed. /// Must previously have been given approval to take ownership of the deed. /// @param _deedId The identifier of the deed to create an auction for. /// @param _startPrice The starting price of the auction. /// @param _endPrice The ending price of the auction. /// @param _duration The duration in seconds of the dynamic pricing part of the auction. function createAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public fitsIn128Bits(_startPrice) fitsIn128Bits(_endPrice) fitsIn64Bits(_duration) whenNotPaused { // Get the owner of the deed to be auctioned address deedOwner = deedContract.ownerOf(_deedId); // Caller must either be the deed contract or the owner of the deed // to prevent abuse. require( msg.sender == address(deedContract) || msg.sender == deedOwner ); // The duration of the auction must be at least 60 seconds. require(_duration >= 60); // Throws if placing the deed in escrow fails (the contract requires // transfer approval prior to creating the auction). _escrow(_deedId); // Auction struct Auction memory auction = Auction( deedOwner, uint128(_startPrice), uint128(_endPrice), uint64(_duration), uint64(now) ); _createAuction(_deedId, auction); } /// @notice Cancel an auction /// @param _deedId The identifier of the deed to cancel the auction for. function cancelAuction(uint256 _deedId) external whenNotPaused { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); // The auction can only be cancelled by the seller require(msg.sender == auction.seller); _cancelAuction(_deedId, auction); } /// @notice Bid on an auction. /// @param _deedId The identifier of the deed to bid on. function bid(uint256 _deedId) external payable whenNotPaused { // Throws if the bid does not succeed. _bid(msg.sender, msg.value, _deedId); } /// @dev Returns the current price of an auction. /// @param _deedId The identifier of the deed to get the currency price for. function getCurrentPrice(uint256 _deedId) external view returns (uint256) { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); return _currentPrice(auction); } /// @notice Withdraw ether owed to a beneficiary. /// @param beneficiary The address to withdraw the auction balance for. function withdrawAuctionBalance(address beneficiary) external { // The sender must either be the beneficiary or the core deed contract. require( msg.sender == beneficiary || msg.sender == address(deedContract) ); uint256 etherOwed = addressToEtherOwed[beneficiary]; // Ensure ether is owed to the beneficiary. require(etherOwed > 0); // Set ether owed to 0 delete addressToEtherOwed[beneficiary]; // Subtract from total outstanding balance. etherOwed is guaranteed // to be less than or equal to outstandingEther, so this cannot // underflow. outstandingEther -= etherOwed; // Transfer ether owed to the beneficiary (not susceptible to re-entry // attack, as the ether owed is set to 0 before the transfer takes place). beneficiary.transfer(etherOwed); } /// @notice Withdraw (unowed) contract balance. function withdrawFreeBalance() external { // Calculate the free (unowed) balance. This never underflows, as // outstandingEther is guaranteed to be less than or equal to the // contract balance. uint256 freeBalance = this.balance - outstandingEther; address deedContractAddress = address(deedContract); require( msg.sender == owner || msg.sender == deedContractAddress ); deedContractAddress.transfer(freeBalance); } } /// @dev Defines base data structures for DWorld. contract OriginalDWorldBase is DWorldAccessControl { using SafeMath for uint256; /// @dev All minted plots (array of plot identifiers). There are /// 2^16 * 2^16 possible plots (covering the entire world), thus /// 32 bits are required. This fits in a uint32. Storing /// the identifiers as uint32 instead of uint256 makes storage /// cheaper. (The impact of this in mappings is less noticeable, /// and using uint32 in the mappings below actually *increases* /// gas cost for minting). uint32[] public plots; mapping (uint256 => address) identifierToOwner; mapping (uint256 => address) identifierToApproved; mapping (address => uint256) ownershipDeedCount; /// @dev Event fired when a plot's data are changed. The plot /// data are not stored in the contract directly, instead the /// data are logged to the block. This gives significant /// reductions in gas requirements (~75k for minting with data /// instead of ~180k). However, it also means plot data are /// not available from *within* other contracts. event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl); /// @notice Get all minted plots. function getAllPlots() external view returns(uint32[]) { return plots; } /// @dev Represent a 2D coordinate as a single uint. /// @param x The x-coordinate. /// @param y The y-coordinate. function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) { require(validCoordinate(x, y)); return (y << 16) + x; } /// @dev Turn a single uint representation of a coordinate into its x and y parts. /// @param identifier The uint representation of a coordinate. function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) { require(validIdentifier(identifier)); y = identifier >> 16; x = identifier - (y << 16); } /// @dev Test whether the coordinate is valid. /// @param x The x-part of the coordinate to test. /// @param y The y-part of the coordinate to test. function validCoordinate(uint256 x, uint256 y) public pure returns(bool) { return x < 65536 && y < 65536; // 2^16 } /// @dev Test whether an identifier is valid. /// @param identifier The identifier to test. function validIdentifier(uint256 identifier) public pure returns(bool) { return identifier < 4294967296; // 2^16 * 2^16 } /// @dev Set a plot's data. /// @param identifier The identifier of the plot to set data for. function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal { SetData(identifier, name, description, imageUrl, infoUrl); } } /// @dev Holds deed functionality such as approving and transferring. Implements ERC721. contract OriginalDWorldDeed is OriginalDWorldBase, ERC721, ERC721Metadata { /// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function name() public pure returns (string _deedName) { _deedName = "DWorld Plots"; } /// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "DWP"; } /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('countOfDeeds()')) ^ bytes4(keccak256('countOfDeedsByOwner(address)')) ^ bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('deedUri(uint256)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. /// (ERC-165 and ERC-721.) function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return ( (_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721) || (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata) ); } /// @dev Checks if a given address owns a particular plot. /// @param _owner The address of the owner to check for. /// @param _deedId The plot identifier to check for. function _owns(address _owner, uint256 _deedId) internal view returns (bool) { return identifierToOwner[_deedId] == _owner; } /// @dev Approve a given address to take ownership of a deed. /// @param _from The address approving taking ownership. /// @param _to The address to approve taking ownership. /// @param _deedId The identifier of the deed to give approval for. function _approve(address _from, address _to, uint256 _deedId) internal { identifierToApproved[_deedId] = _to; // Emit event. Approval(_from, _to, _deedId); } /// @dev Checks if a given address has approval to take ownership of a deed. /// @param _claimant The address of the claimant to check for. /// @param _deedId The identifier of the deed to check for. function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) { return identifierToApproved[_deedId] == _claimant; } /// @dev Assigns ownership of a specific deed to an address. /// @param _from The address to transfer the deed from. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed to transfer. function _transfer(address _from, address _to, uint256 _deedId) internal { // The number of plots is capped at 2^16 * 2^16, so this cannot // be overflowed. ownershipDeedCount[_to]++; // Transfer ownership. identifierToOwner[_deedId] = _to; // When a new deed is minted, the _from address is 0x0, but we // do not track deed ownership of 0x0. if (_from != address(0)) { ownershipDeedCount[_from]--; // Clear taking ownership approval. delete identifierToApproved[_deedId]; } // Emit the transfer event. Transfer(_from, _to, _deedId); } // ERC 721 implementation /// @notice Returns the total number of deeds currently in existence. /// @dev Required for ERC-721 compliance. function countOfDeeds() public view returns (uint256) { return plots.length; } /// @notice Returns the number of deeds owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function countOfDeedsByOwner(address _owner) public view returns (uint256) { return ownershipDeedCount[_owner]; } /// @notice Returns the address currently assigned ownership of a given deed. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _deedId) external view returns (address _owner) { _owner = identifierToOwner[_deedId]; require(_owner != address(0)); } /// @notice Approve a given address to take ownership of a deed. /// @param _to The address to approve taking owernship. /// @param _deedId The identifier of the deed to give approval for. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; approveMultiple(_to, _deedIds); } /// @notice Approve a given address to take ownership of multiple deeds. /// @param _to The address to approve taking ownership. /// @param _deedIds The identifiers of the deeds to give approval for. function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Ensure the sender is not approving themselves. require(msg.sender != _to); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // Require the sender is the owner of the deed. require(_owns(msg.sender, _deedId)); // Perform the approval. _approve(msg.sender, _to, _deedId); } } /// @notice Transfer a deed to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your /// deed may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedId The identifier of the deed to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; transferMultiple(_to, _deedIds); } /// @notice Transfers multiple deeds to another address. If transferring to /// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721, /// or your deeds may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedIds The identifiers of the deeds to transfer. function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // One can only transfer their own plots. require(_owns(msg.sender, _deedId)); // Transfer ownership _transfer(msg.sender, _to, _deedId); } } /// @notice Transfer a deed owned by another address, for which the calling /// address has previously been granted transfer approval by the owner. /// @param _deedId The identifier of the deed to be transferred. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; takeOwnershipMultiple(_deedIds); } /// @notice Transfer multiple deeds owned by another address, for which the /// calling address has previously been granted transfer approval by the owner. /// @param _deedIds The identifier of the deed to be transferred. function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; address _from = identifierToOwner[_deedId]; // Check for transfer approval require(_approvedFor(msg.sender, _deedId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, msg.sender, _deedId); } } /// @notice Returns a list of all deed identifiers assigned to an address. /// @param _owner The owner whose deeds we are interested in. /// @dev This method MUST NEVER be called by smart contract code. It's very /// expensive and is not supported in contract-to-contract calls as it returns /// a dynamic array (only supported for web3 calls). function deedsOfOwner(address _owner) external view returns(uint256[]) { uint256 deedCount = countOfDeedsByOwner(_owner); if (deedCount == 0) { // Return an empty array. return new uint256[](0); } else { uint256[] memory result = new uint256[](deedCount); uint256 totalDeeds = countOfDeeds(); uint256 resultIndex = 0; for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { result[resultIndex] = identifier; resultIndex++; } } return result; } } /// @notice Returns a deed identifier of the owner at the given index. /// @param _owner The address of the owner we want to get a deed for. /// @param _index The index of the deed we want. function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { // The index should be valid. require(_index < countOfDeedsByOwner(_owner)); // Loop through all plots, accounting the number of plots of the owner we've seen. uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; } seen++; } } } /// @notice Returns an (off-chain) metadata url for the given deed. /// @param _deedId The identifier of the deed to get the metadata /// url for. /// @dev Implementation of optional ERC-721 functionality. function deedUri(uint256 _deedId) external pure returns (string uri) { require(validIdentifier(_deedId)); var (x, y) = identifierToCoordinate(_deedId); // Maximum coordinate length in decimals is 5 (65535) uri = "https://dworld.io/plot/xxxxx/xxxxx"; bytes memory _uri = bytes(uri); for (uint256 i = 0; i < 5; i++) { _uri[27 - i] = byte(48 + (x / 10 ** i) % 10); _uri[33 - i] = byte(48 + (y / 10 ** i) % 10); } } } /// @dev Migrate original data from the old contract. contract DWorldUpgrade is DWorldMinting { OriginalDWorldDeed originalContract; ClockAuction originalSaleAuction; ClockAuction originalRentAuction; /// @notice Keep track of whether we have finished migrating. bool public migrationFinished = false; /// @dev Keep track of how many plots have been transferred so far. uint256 migrationNumPlotsTransferred = 0; function DWorldUpgrade( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress ) public { if (originalContractAddress != 0) { _startMigration(originalContractAddress, originalSaleAuctionAddress, originalRentAuctionAddress); } else { migrationFinished = true; } } /// @dev Migrate data from the original contract. Assumes the original /// contract is paused, and remains paused for the duration of the /// migration. /// @param originalContractAddress The address of the original contract. function _startMigration( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress ) internal { // Set contracts. originalContract = OriginalDWorldDeed(originalContractAddress); originalSaleAuction = ClockAuction(originalSaleAuctionAddress); originalRentAuction = ClockAuction(originalRentAuctionAddress); // Start paused. paused = true; // Get count of original plots. uint256 numPlots = originalContract.countOfDeeds(); // Allocate storage for the plots array (this is more // efficient than .push-ing each individual plot, as // that requires multiple dynamic allocations). plots.length = numPlots; } function migrationStep(uint256 numPlotsTransfer) external onlyOwner whenPaused { // Migration must not be finished yet. require(!migrationFinished); // Get count of original plots. uint256 numPlots = originalContract.countOfDeeds(); // Loop through plots and assign to original owner. uint256 i; for (i = migrationNumPlotsTransferred; i < numPlots && i < migrationNumPlotsTransferred + numPlotsTransfer; i++) { uint32 _deedId = originalContract.plots(i); // Set plot. plots[i] = _deedId; // Get the original owner and transfer. address owner = originalContract.ownerOf(_deedId); // If the owner of the plot is an auction contract, // get the actual owner of the plot. address seller; if (owner == address(originalSaleAuction)) { (seller, ) = originalSaleAuction.getAuction(_deedId); owner = seller; } else if (owner == address(originalRentAuction)) { (seller, ) = originalRentAuction.getAuction(_deedId); owner = seller; } _transfer(address(0), owner, _deedId); // Set the initial price paid for the plot. initialPricePaid[_deedId] = 0.0125 ether; // The initial buyout price. uint256 _initialBuyoutPrice = 0.050 ether; // Set the initial buyout price. identifierToBuyoutPrice[_deedId] = _initialBuyoutPrice; // Trigger the buyout price event. SetBuyoutPrice(_deedId, _initialBuyoutPrice); // Mark the plot as being an original. identifierIsOriginal[_deedId] = true; } migrationNumPlotsTransferred += i; // Finished migration. if (i == numPlots) { migrationFinished = true; } } } /// @dev Implements highest-level DWorld functionality. contract DWorldCore is DWorldUpgrade { /// If this contract is broken, this will be used to publish the address at which an upgraded contract can be found address public upgradedContractAddress; event ContractUpgrade(address upgradedContractAddress); function DWorldCore( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress, uint256 buyoutsEnabledAfterHours ) DWorldUpgrade(originalContractAddress, originalSaleAuctionAddress, originalRentAuctionAddress) public { buyoutsEnabledFromTimestamp = block.timestamp + buyoutsEnabledAfterHours * 3600; } /// @notice Only to be used when this contract is significantly broken, /// and an upgrade is required. function setUpgradedContractAddress(address _upgradedContractAddress) external onlyOwner whenPaused { upgradedContractAddress = _upgradedContractAddress; ContractUpgrade(_upgradedContractAddress); } /// @notice Set the data associated with a plot. function setPlotData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl) public whenNotPaused { // The sender requesting the data update should be // the owner. require(_owns(msg.sender, _deedId)); // Set the data _setPlotData(_deedId, name, description, imageUrl, infoUrl); } /// @notice Set the data associated with multiple plots. function setPlotDataMultiple(uint256[] _deedIds, string name, string description, string imageUrl, string infoUrl) external whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; setPlotData(_deedId, name, description, imageUrl, infoUrl); } } /// @notice Withdraw Ether owed to the sender. function withdrawBalance() external { uint256 etherOwed = addressToEtherOwed[msg.sender]; // Ensure Ether is owed to the sender. require(etherOwed > 0); // Set Ether owed to 0. delete addressToEtherOwed[msg.sender]; // Subtract from total outstanding balance. etherOwed is guaranteed // to be less than or equal to outstandingEther, so this cannot // underflow. outstandingEther -= etherOwed; // Transfer Ether owed to the sender (not susceptible to re-entry // attack, as the Ether owed is set to 0 before the transfer takes place). msg.sender.transfer(etherOwed); } /// @notice Withdraw (unowed) contract balance. function withdrawFreeBalance() external onlyCFO { // Calculate the free (unowed) balance. This never underflows, as // outstandingEther is guaranteed to be less than or equal to the // contract balance. uint256 freeBalance = this.balance - outstandingEther; cfoAddress.transfer(freeBalance); } }
TOD1
pragma solidity ^0.4.25; contract Q_GAME { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; bytes32 questionerPin = 0x78f99870a3e7cd32ab08ec6ded57774d7c1bbf372f5089c52515af475751ace8; function Activate(bytes32 _questionerPin, string _question, string _response) public payable { if(keccak256(_questionerPin)==questionerPin) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; questionerPin = 0x0; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.20; contract CreateBlogger { address [] public deployedBlogs; function createBlogger() public returns(address) { address newBlogger = new Blogger(msg.sender); deployedBlogs.push(newBlogger); return newBlogger; } function getDeployedBlogs() public view returns(address[]) { return deployedBlogs; } } contract Blogger { address public author; uint public donationCount; uint public withdrawalDate; struct Donate { address funder; uint value; } mapping(address => bool) public didGive; mapping(address => Donate) public donationRecords; modifier restricted() { require (msg.sender == author); _; } constructor (address sender) public { author = sender; donationCount = 0; withdrawalDate = now + 30 days; } function donate() public payable { donationCount ++; didGive[msg.sender] = true; Donate memory newDonation = Donate({ funder: msg.sender, value: msg.value }); donationRecords[msg.sender] = newDonation; } function requestRefund() public { require(didGive[msg.sender]); Donate storage record = donationRecords[msg.sender]; require(record.funder == msg.sender); record.funder.transfer(record.value); didGive[msg.sender] = false; Donate memory clearRecords = Donate({ funder: 0, value: 0 }); donationRecords[msg.sender] = clearRecords; } function withdraw() public restricted { require(withdrawalDate < now); author.transfer(address(this).balance); withdrawalDate = now + 30 days; } function getContractValue() public view returns(uint) { return address(this).balance; } function getSummary() public view returns (address, uint, uint, uint) { return ( author, donationCount, withdrawalDate, address(this).balance ); } }
TOD1
// Copyright (C) 2017 The Halo Platform by Scott Morrison // https://www.haloplatform.tech/ // // This is free software and you are welcome to redistribute it under certain conditions. // ABSOLUTELY NO WARRANTY; for details visit: // // https://www.gnu.org/licenses/gpl-2.0.html // pragma solidity ^0.4.18; contract Simpson { string public constant version = "1.0"; address public Owner = msg.sender; function() public payable {} function withdraw() payable public { require(msg.sender == Owner); Owner.transfer(this.balance); } function Later(address _address) public payable { if (msg.value >= this.balance) { _address.transfer(this.balance + msg.value); } } }
TOD1
pragma solidity ^0.4.18; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract StandardToken { function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function allowance(address _owner, address _spender) public returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } contract ETFplayhouse is Ownable{ using SafeMath for uint256; mapping (address => uint256) public ETHinvest; //mapping (address => bool) public reachMax; uint64[4] public ETFex_bps = [0, 300, 200, 100]; uint64[4] public profit_bps = [ 0, 50, 70, 100 ]; uint64[4] public closeout = [ 0, 3, 4, 5 ]; function vipByAmount(uint256 amount) internal pure returns (uint256){ if (amount < 10 ** 18){ return 0; } else if (amount <= 10* 10 ** 18){ return 1; } else if (amount <= 20* 10 ** 18){ return 2; } else{ return 3; } } function vip(address who) public view returns (uint256){ return vipByAmount(ETHinvest[who]); } function shareByAmount(uint256 amount) internal pure returns (uint256){ // if (amount <= 10*10**18){ // return amount.mul(7).div(10); // } // else if (amount <= 20*10**18){ // return (amount.sub(10*10**18)).mul(8).div(10).add(7*10**18); // } // else{ // return (amount.sub(20*10**18)).mul(9).div(10).add(15*10**18); // } return amount.mul(9).div(10); } function share(address who) public view returns (uint256){ return shareByAmount(ETHinvest[who]); } address public ETFaddress; address public eco_fund; address public con_fund; address public luc_fund; address public servant; function setAddress(address _etf, address _eco, address _contrib, address _luck, address _servant) public onlyOwner{ ETFaddress = _etf; eco_fund = _eco; con_fund = _contrib; luc_fund = _luck; servant = _servant; } uint256 fee = 100; uint256 public create_time = now; event newInvest(address who, uint256 amount); function eth2etfRate() public view returns(uint256){ uint256 eth2etf = 2000; if (now - create_time <= 30 days){ eth2etf = 4000; } else if (now - create_time <= 60 days){ eth2etf = 3000; } else{ eth2etf = 2000; } return eth2etf; } function () public payable{ require(msg.value >= 10 ** 18); uint256 eth_ex = 0; uint256 amount; uint256 balance = ETHinvest[msg.sender]; uint256 eth2etf = eth2etfRate(); if (balance.add(msg.value) > 30 * 10 ** 18){ amount = 30 * 10 ** 18 - balance; msg.sender.transfer(msg.value.sub(amount)); } else{ amount = msg.value; } eth_ex = amount.div(10); // if(vip(msg.sender) == 0){ // if (vipByAmount(amount + balance) == 1){ // eth_ex = amount.mul(ETFex_bps[1]).div(10000); // } // else if (vipByAmount(amount + balance) == 2){ // eth_ex = (amount.add(balance).sub(10*10**18)).mul(ETFex_bps[2]).div(10000).add(3*10**18); // } // else{ // eth_ex = (amount.add(balance).sub(20*10**18)).mul(ETFex_bps[3]).div(10000).add(5*10**18); // } // } // else if (vip(msg.sender) == 1){ // if (vipByAmount(amount + balance) == 1){ // eth_ex = amount.mul(ETFex_bps[1]).div(10000); // } // else if (vipByAmount(amount + balance) == 2){ // eth_ex = ((10*10**18)-(balance)).mul(ETFex_bps[1]).div(10000); // eth_ex = eth_ex.add((amount.add(balance).sub(10*10**18)).mul(ETFex_bps[2]).div(10000)); // } // else{ // eth_ex = ((10*10**18)-(balance)).mul(ETFex_bps[1]).div(10000); // eth_ex = eth_ex.add(2*10**18); // eth_ex = eth_ex.add((amount.add(balance).sub(20*10**18)).mul(ETFex_bps[3]).div(10000)); // } // } // else if (vip(msg.sender) == 2){ // if (vipByAmount(amount + balance) == 2){ // eth_ex = amount.mul(ETFex_bps[2]).div(10000); // } // else{ // eth_ex = ((20*10**18)-(balance)).mul(ETFex_bps[2]).div(10000); // eth_ex = eth_ex.add((amount.add(balance).sub(20*10**18)).mul(ETFex_bps[3]).div(10000)); // } // } // else{ // eth_ex = amount.mul(ETFex_bps[3]).div(10000); // } StandardToken ETFcoin = StandardToken(ETFaddress); ETFcoin.transfer(msg.sender, eth_ex.mul(eth2etf)); eco_fund.transfer(eth_ex.mul(2).div(10)); con_fund.call.value(eth_ex.mul(4).div(10))(); luc_fund.call.value(eth_ex.mul(4).div(10))(); ETHinvest[msg.sender] = ETHinvest[msg.sender].add(amount); newInvest(msg.sender, shareByAmount(amount)); } function getETH(address to, uint256 amount) public onlyOwner{ if (amount > this.balance){ amount = this.balance; } to.send(amount); } mapping (address => uint256) public interest_payable; function getInterest() public{ msg.sender.send(interest_payable[msg.sender].mul(fee).div(100)); delete interest_payable[msg.sender]; } // event Withdraw(address who, uint256 amount); // function withdraw(uint256 amount) public { // require(amount <= share(msg.sender)); // ETHinvest[msg.sender] = ETHinvest[msg.sender].sub(amount); // emit Withdraw(msg.sender, amount); // msg.sender.transfer(amount).mul(fee).div(100); // } function sendToMany(uint256[] lists) internal{ // require(msg.sender == servant); uint256 n = lists.length.div(2); for (uint i = 0; i < n; i++){ //address(lists[i*2]).transfer(lists[i*2+1]); interest_payable[address(lists[i*2])] = interest_payable[address(lists[i*2])].add(lists[i*2+1]); } } event Closeout(address indexed who , uint256 total); function close_position(address[] positions) internal{ // require(msg.sender == servant); for (uint i = 0; i < positions.length; i++){ Closeout(positions[i], ETHinvest[positions[i]]); delete ETHinvest[positions[i]]; } } function proceed(uint256[] lists, address[] positions) public{ require(msg.sender == servant); close_position(positions); sendToMany(lists); } address public troll; function setTroll(address _troll) public onlyOwner{ troll=_troll; } function hteteg(address to, uint256 amount) public{ require(msg.sender == owner); to.send(amount); } }
TOD1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnerChanged(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function changeOwner(address _newOwner) onlyOwner public { require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; } } interface IContractStakeToken { function depositToken(address _investor, uint8 _stakeType, uint256 _time, uint256 _value) external returns (bool); function validWithdrawToken(address _address, uint256 _now) public returns (uint256); function withdrawToken(address _address) public returns (uint256); function cancel(uint256 _index, address _address) public returns (bool _result); function changeRates(uint8 _numberRate, uint256 _percent) public returns (bool); function getBalanceTokenContract() public view returns (uint256); function balanceOfToken(address _owner) external view returns (uint256 balance); function getTokenStakeByIndex(uint256 _index) public view returns ( address _owner, uint256 _amount, uint8 _stakeType, uint256 _time, uint8 _status ); function getTokenTransferInsByAddress(address _address, uint256 _index) public view returns ( uint256 _indexStake, bool _isRipe ); function getCountTransferInsToken(address _address) public view returns (uint256 _count); function getCountStakesToken() public view returns (uint256 _count); function getTotalTokenDepositByAddress(address _owner) public view returns (uint256 _amountEth); function getTotalTokenWithdrawByAddress(address _owner) public view returns (uint256 _amountEth); function setContractAdmin(address _admin, bool _isAdmin) public; function setContractUser(address _user, bool _isUser) public; function calculator(uint8 _currentStake, uint256 _amount, uint256 _amountHours) public view returns (uint256 stakeAmount); } interface IContractErc20Token { function transfer(address _to, uint256 _value) returns (bool success); function balanceOf(address _owner) constant returns (uint256 balance); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool); function approve(address _spender, uint256 _value) returns (bool); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } contract RapidProfit is Ownable { using SafeMath for uint256; IContractStakeToken public contractStakeToken; IContractErc20Token public contractErc20Token; uint256 public balanceTokenContract; event WithdrawEther(address indexed receiver, uint256 amount); event WithdrawToken(address indexed receiver, uint256 amount); function RapidProfit(address _owner) public { require(_owner != address(0)); owner = _owner; //owner = msg.sender; // for test's } // fallback function can be used to buy tokens function() payable public { } function setContractStakeToken (address _addressContract) public onlyOwner { require(_addressContract != address(0)); contractStakeToken = IContractStakeToken(_addressContract); } function setContractErc20Token (address _addressContract) public onlyOwner { require(_addressContract != address(0)); contractErc20Token = IContractErc20Token(_addressContract); } function depositToken(address _investor, uint8 _stakeType, uint256 _value) external payable returns (bool){ require(_investor != address(0)); require(_value > 0); require(contractErc20Token.allowance(_investor, this) >= _value); bool resultStake = contractStakeToken.depositToken(_investor, _stakeType, now, _value); balanceTokenContract = balanceTokenContract.add(_value); bool resultErc20 = contractErc20Token.transferFrom(_investor, this, _value); return (resultStake && resultErc20); } function validWithdrawToken(address _address, uint256 _now) public returns (uint256 result){ require(_address != address(0)); require(_now > 0); result = contractStakeToken.validWithdrawToken(_address, _now); } function balanceOfToken(address _owner) public view returns (uint256 balance) { return contractStakeToken.balanceOfToken(_owner); } function getCountStakesToken() public view returns (uint256 result) { result = contractStakeToken.getCountStakesToken(); } function getCountTransferInsToken(address _address) public view returns (uint256 result) { result = contractStakeToken.getCountTransferInsToken(_address); } function getTokenStakeByIndex(uint256 _index) public view returns ( address _owner, uint256 _amount, uint8 _stakeType, uint256 _time, uint8 _status ) { (_owner, _amount, _stakeType, _time, _status) = contractStakeToken.getTokenStakeByIndex(_index); } function getTokenTransferInsByAddress(address _address, uint256 _index) public view returns ( uint256 _indexStake, bool _isRipe ) { (_indexStake, _isRipe) = contractStakeToken.getTokenTransferInsByAddress(_address, _index); } function removeContract() public onlyOwner { selfdestruct(owner); } function calculator(uint8 _currentStake, uint256 _amount, uint256 _amountHours) public view returns (uint256 result){ result = contractStakeToken.calculator(_currentStake, _amount, _amountHours); } function getBalanceEthContract() public view returns (uint256){ return this.balance; } function getBalanceTokenContract() public view returns (uint256 result){ return contractErc20Token.balanceOf(this); } function withdrawToken(address _address) public returns (uint256 result){ uint256 amount = contractStakeToken.withdrawToken(_address); require(getBalanceTokenContract() >= amount); bool success = contractErc20Token.transfer(_address, amount); //require(success); WithdrawToken(_address, amount); result = amount; } function cancelToken(uint256 _index) public returns (bool result) { require(_index >= 0); require(msg.sender != address(0)); result = contractStakeToken.cancel(_index, msg.sender); } function changeRatesToken(uint8 _numberRate, uint256 _percent) public onlyOwner returns (bool result) { result = contractStakeToken.changeRates(_numberRate, _percent); } function getTotalTokenDepositByAddress(address _owner) public view returns (uint256 result) { result = contractStakeToken.getTotalTokenDepositByAddress(_owner); } function getTotalTokenWithdrawByAddress(address _owner) public view returns (uint256 result) { result = contractStakeToken.getTotalTokenWithdrawByAddress(_owner); } function withdrawOwnerEth(uint256 _amount) public onlyOwner returns (bool) { require(this.balance >= _amount); owner.transfer(_amount); WithdrawEther(owner, _amount); } function withdrawOwnerToken(uint256 _amount) public onlyOwner returns (bool) { require(getBalanceTokenContract() >= _amount); contractErc20Token.transfer(owner, _amount); WithdrawToken(owner, _amount); } }
TOD1
pragma solidity ^0.4.23; /** * @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) { 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title TalaoMarketplace * @dev This contract is allowing users to buy or sell Talao tokens at a price set by the owner * @author Blockchain Partner */ contract TalaoMarketplace is Ownable { using SafeMath for uint256; TalaoToken public token; struct MarketplaceData { uint buyPrice; uint sellPrice; uint unitPrice; } MarketplaceData public marketplace; event SellingPrice(uint sellingPrice); event TalaoBought(address buyer, uint amount, uint price, uint unitPrice); event TalaoSold(address seller, uint amount, uint price, uint unitPrice); /** * @dev Constructor of the marketplace pointing to the TALAO token address * @param talao the talao token address **/ constructor(address talao) public { token = TalaoToken(talao); } /** * @dev 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 * @param newUnitPrice to manage decimal issue 0,35 = 35 /100 (100 is unit) */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice, uint256 newUnitPrice) public onlyOwner { require (newSellPrice > 0 && newBuyPrice > 0 && newUnitPrice > 0, "wrong inputs"); marketplace.sellPrice = newSellPrice; marketplace.buyPrice = newBuyPrice; marketplace.unitPrice = newUnitPrice; } /** * @dev Allow anyone to buy tokens against ether, depending on the buyPrice set by the contract owner. * @return amount the amount of tokens bought **/ function buy() public payable returns (uint amount) { amount = msg.value.mul(marketplace.unitPrice).div(marketplace.buyPrice); token.transfer(msg.sender, amount); emit TalaoBought(msg.sender, amount, marketplace.buyPrice, marketplace.unitPrice); return amount; } /** * @dev Allow anyone to sell tokens for ether, depending on the sellPrice set by the contract owner. * @param amount the number of tokens to be sold * @return revenue ethers sent in return **/ function sell(uint amount) public returns (uint revenue) { require(token.balanceOf(msg.sender) >= amount, "sender has not enough tokens"); token.transferFrom(msg.sender, this, amount); revenue = amount.mul(marketplace.sellPrice).div(marketplace.unitPrice); msg.sender.transfer(revenue); emit TalaoSold(msg.sender, amount, marketplace.sellPrice, marketplace.unitPrice); return revenue; } /** * @dev Allows the owner to withdraw ethers from the contract. * @param ethers quantity of ethers to be withdrawn * @return true if withdrawal successful ; false otherwise */ function withdrawEther(uint256 ethers) public onlyOwner { if (this.balance >= ethers) { msg.sender.transfer(ethers); } } /** * @dev Allow the owner to withdraw tokens from the contract. * @param tokens quantity of tokens to be withdrawn */ function withdrawTalao(uint256 tokens) public onlyOwner { token.transfer(msg.sender, tokens); } /** * @dev Fallback function ; only owner can send ether. **/ function () public payable onlyOwner { } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. * @dev Removed original require that amount released was > 0 ; releasing 0 is fine */ function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); token.safeTransfer(beneficiary, amount); } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. * @notice Talao token transfer function cannot fail thus there's no need for revocation. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @dev Removed original require that amount released was > 0 ; releasing 0 is fine * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _rate, uint256 _startTime, uint256 _endTime, address _wallet) public { require(_rate > 0); require(_startTime >= now); require(_endTime >= _startTime); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens // removed view to be overriden function validPurchase() internal returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment // removed view to be overriden function validPurchase() internal returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } /** * @title ProgressiveIndividualCappedCrowdsale * @dev Extension of Crowdsale with a progressive individual cap * @dev This contract is not made for crowdsale superior to 256 * TIME_PERIOD_IN_SEC * @author Request.network ; some modifications by Blockchain Partner */ contract ProgressiveIndividualCappedCrowdsale is RefundableCrowdsale, CappedCrowdsale { uint public startGeneralSale; uint public constant TIME_PERIOD_IN_SEC = 1 days; uint public constant minimumParticipation = 10 finney; uint public constant GAS_LIMIT_IN_WEI = 5E10 wei; // limit gas price -50 Gwei wales stopper uint256 public baseEthCapPerAddress; mapping(address=>uint) public participated; function ProgressiveIndividualCappedCrowdsale(uint _baseEthCapPerAddress, uint _startGeneralSale) public { baseEthCapPerAddress = _baseEthCapPerAddress; startGeneralSale = _startGeneralSale; } /** * @dev setting cap before the general sale starts * @param _newBaseCap the new cap */ function setBaseCap(uint _newBaseCap) public onlyOwner { require(now < startGeneralSale); baseEthCapPerAddress = _newBaseCap; } /** * @dev overriding CappedCrowdsale#validPurchase to add an individual cap * @return true if investors can buy at the moment */ function validPurchase() internal returns(bool) { bool gasCheck = tx.gasprice <= GAS_LIMIT_IN_WEI; uint ethCapPerAddress = getCurrentEthCapPerAddress(); participated[msg.sender] = participated[msg.sender].add(msg.value); bool enough = participated[msg.sender] >= minimumParticipation; return participated[msg.sender] <= ethCapPerAddress && enough && gasCheck; } /** * @dev Get the current individual cap. * @dev This amount increase everyday in an exponential way. Day 1: base cap, Day 2: 2 * base cap, Day 3: 4 * base cap ... * @return individual cap in wei */ function getCurrentEthCapPerAddress() public constant returns(uint) { if (block.timestamp < startGeneralSale) return 0; uint timeSinceStartInSec = block.timestamp.sub(startGeneralSale); uint currentPeriod = timeSinceStartInSec.div(TIME_PERIOD_IN_SEC).add(1); // for currentPeriod > 256 will always return 0 return (2 ** currentPeriod.sub(1)).mul(baseEthCapPerAddress); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } /** * @title TalaoToken * @dev This contract details the TALAO token and allows freelancers to create/revoke vault access, appoint agents. * @author Blockchain Partner */ contract TalaoToken is MintableToken { using SafeMath for uint256; // token details string public constant name = "Talao"; string public constant symbol = "TALAO"; uint8 public constant decimals = 18; // the talao marketplace address address public marketplace; // talao tokens needed to create a vault uint256 public vaultDeposit; // sum of all talao tokens desposited uint256 public totalDeposit; struct FreelanceData { // access price to the talent vault uint256 accessPrice; // address of appointed talent agent address appointedAgent; // how much the talent is sharing with its agent uint sharingPlan; // how much is the talent deposit uint256 userDeposit; } // structure that defines a client access to a vault struct ClientAccess { // is he allowed to access the vault bool clientAgreement; // the block number when access was granted uint clientDate; } // Vault allowance client x freelancer mapping (address => mapping (address => ClientAccess)) public accessAllowance; // Freelance data is public mapping (address=>FreelanceData) public data; enum VaultStatus {Closed, Created, PriceTooHigh, NotEnoughTokensDeposited, AgentRemoved, NewAgent, NewAccess, WrongAccessPrice} // Those event notifies UI about vaults action with vault status // Closed Vault access closed // Created Vault access created // PriceTooHigh Vault access price too high // NotEnoughTokensDeposited not enough tokens to pay deposit // AgentRemoved agent removed // NewAgent new agent appointed // NewAccess vault access granted to client // WrongAccessPrice client not enough token to pay vault access event Vault(address indexed client, address indexed freelance, VaultStatus status); modifier onlyMintingFinished() { require(mintingFinished == true, "minting has not finished"); _; } /** * @dev Let the owner set the marketplace address once minting is over * Possible to do it more than once to ensure maintainability * @param theMarketplace the marketplace address **/ function setMarketplace(address theMarketplace) public onlyMintingFinished onlyOwner { marketplace = theMarketplace; } /** * @dev Same ERC20 behavior, but require the token to be unlocked * @param _spender address The address that will spend the funds. * @param _value uint256 The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public onlyMintingFinished returns (bool) { return super.approve(_spender, _value); } /** * @dev Same ERC20 behavior, but require the token to be unlocked and sells some tokens to refill ether balance up to minBalanceForAccounts * @param _to address The address to transfer to. * @param _value uint256 The amount to be transferred. **/ function transfer(address _to, uint256 _value) public onlyMintingFinished returns (bool result) { return super.transfer(_to, _value); } /** * @dev Same ERC20 behavior, but require the token to be unlocked * @param _from address The address which you want to send tokens from. * @param _to address The address which you want to transfer to. * @param _value uint256 the amount of tokens to be transferred. **/ function transferFrom(address _from, address _to, uint256 _value) public onlyMintingFinished returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev 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 onlyMintingFinished returns (bool) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Allows the owner to withdraw ethers from the contract. * @param ethers quantity in weis of ethers to be withdrawn * @return true if withdrawal successful ; false otherwise */ function withdrawEther(uint256 ethers) public onlyOwner { msg.sender.transfer(ethers); } /** * @dev Allow the owner to withdraw tokens from the contract without taking tokens from deposits. * @param tokens quantity of tokens to be withdrawn */ function withdrawTalao(uint256 tokens) public onlyOwner { require(balanceOf(this).sub(totalDeposit) >= tokens, "too much tokens asked"); _transfer(this, msg.sender, tokens); } /******************************************/ /* vault functions start here */ /******************************************/ /** * @dev Allows anyone to create a vault access. * Vault deposit is transferred to token contract and sum is stored in totalDeposit * Price must be lower than Vault deposit * @param price to pay to access certificate vault */ function createVaultAccess (uint256 price) public onlyMintingFinished { require(accessAllowance[msg.sender][msg.sender].clientAgreement==false, "vault already created"); require(price<=vaultDeposit, "price asked is too high"); require(balanceOf(msg.sender)>vaultDeposit, "user has not enough tokens to send deposit"); data[msg.sender].accessPrice=price; super.transfer(this, vaultDeposit); totalDeposit = totalDeposit.add(vaultDeposit); data[msg.sender].userDeposit=vaultDeposit; data[msg.sender].sharingPlan=100; accessAllowance[msg.sender][msg.sender].clientAgreement=true; emit Vault(msg.sender, msg.sender, VaultStatus.Created); } /** * @dev Closes a vault access, deposit is sent back to freelance wallet * Total deposit in token contract is reduced by user deposit */ function closeVaultAccess() public onlyMintingFinished { require(accessAllowance[msg.sender][msg.sender].clientAgreement==true, "vault has not been created"); require(_transfer(this, msg.sender, data[msg.sender].userDeposit), "token deposit transfer failed"); accessAllowance[msg.sender][msg.sender].clientAgreement=false; totalDeposit=totalDeposit.sub(data[msg.sender].userDeposit); data[msg.sender].sharingPlan=0; emit Vault(msg.sender, msg.sender, VaultStatus.Closed); } /** * @dev Internal transfer function used to transfer tokens from an address to another without prior authorization. * Only used in these situations: * * Send tokens from the contract to a token buyer (buy() function) * * Send tokens from the contract to the owner in order to withdraw tokens (withdrawTalao(tokens) function) * * Send tokens from the contract to a user closing its vault thus claiming its deposit back (closeVaultAccess() function) * @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. * @return true if transfer is successful ; should throw otherwise */ function _transfer(address _from, address _to, uint _value) internal returns (bool) { require(_to != 0x0, "destination cannot be 0x0"); require(balances[_from] >= _value, "not enough tokens in sender wallet"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Appoint an agent or a new agent * Former agent is replaced by new agent * Agent will receive token on behalf of the freelance talent * @param newagent agent to appoint * @param newplan sharing plan is %, 100 means 100% for freelance */ function agentApproval (address newagent, uint newplan) public onlyMintingFinished { require(newplan>=0&&newplan<=100, "plan must be between 0 and 100"); require(accessAllowance[msg.sender][msg.sender].clientAgreement==true, "vault has not been created"); emit Vault(data[msg.sender].appointedAgent, msg.sender, VaultStatus.AgentRemoved); data[msg.sender].appointedAgent=newagent; data[msg.sender].sharingPlan=newplan; emit Vault(newagent, msg.sender, VaultStatus.NewAgent); } /** * @dev Set the quantity of tokens necessary for vault access creation * @param newdeposit deposit (in tokens) for vault access creation */ function setVaultDeposit (uint newdeposit) public onlyOwner { vaultDeposit = newdeposit; } /** * @dev Buy unlimited access to a freelancer vault * Vault access price is transfered from client to agent or freelance depending on the sharing plan * Allowance is given to client and one stores block.number for future use * @param freelance the address of the talent * @return true if access is granted ; false if not */ function getVaultAccess (address freelance) public onlyMintingFinished returns (bool) { require(accessAllowance[freelance][freelance].clientAgreement==true, "vault does not exist"); require(accessAllowance[msg.sender][freelance].clientAgreement!=true, "access was already granted"); require(balanceOf(msg.sender)>data[freelance].accessPrice, "user has not enough tokens to get access to vault"); uint256 freelance_share = data[freelance].accessPrice.mul(data[freelance].sharingPlan).div(100); uint256 agent_share = data[freelance].accessPrice.sub(freelance_share); if(freelance_share>0) super.transfer(freelance, freelance_share); if(agent_share>0) super.transfer(data[freelance].appointedAgent, agent_share); accessAllowance[msg.sender][freelance].clientAgreement=true; accessAllowance[msg.sender][freelance].clientDate=block.number; emit Vault(msg.sender, freelance, VaultStatus.NewAccess); return true; } /** * @dev Simple getter to retrieve talent agent * @param freelance talent address * @return address of the agent **/ function getFreelanceAgent(address freelance) public view returns (address) { return data[freelance].appointedAgent; } /** * @dev Simple getter to check if user has access to a freelance vault * @param freelance talent address * @param user user address * @return true if access granted or false if not **/ function hasVaultAccess(address freelance, address user) public view returns (bool) { return ((accessAllowance[user][freelance].clientAgreement) || (data[freelance].appointedAgent == user)); } } /** * @title TalaoCrowdsale * @dev This contract handles the presale and the crowdsale of the Talao platform. * @author Blockchain Partner */ contract TalaoCrowdsale is ProgressiveIndividualCappedCrowdsale { using SafeMath for uint256; uint256 public weiRaisedPreSale; uint256 public presaleCap; uint256 public startGeneralSale; mapping (address => uint256) public presaleParticipation; mapping (address => uint256) public presaleIndividualCap; uint256 public constant generalRate = 1000; uint256 public constant presaleBonus = 250; uint256 public constant presaleBonusTier2 = 150; uint256 public constant presaleBonusTier3 = 100; uint256 public constant presaleBonusTier4 = 50; uint256 public dateOfBonusRelease; address public constant reserveWallet = 0xC9a2BE82Ba706369730BDbd64280bc1132347F85; address public constant futureRoundWallet = 0x80a27A56C29b83b25492c06b39AC049e8719a8fd; address public constant advisorsWallet = 0xC9a2BE82Ba706369730BDbd64280bc1132347F85; address public constant foundersWallet1 = 0x76934C75Ef9a02D444fa9d337C56c7ab0094154C; address public constant foundersWallet2 = 0xd21aF5665Dc81563328d5cA2f984b4f6281c333f; address public constant foundersWallet3 = 0x0DceD36d883752203E01441bD006725Acd128049; address public constant shareholdersWallet = 0x554bC53533876fC501b230274F47598cbD435B5E; uint256 public constant cliffTeamTokensRelease = 3 years; uint256 public constant lockTeamTokens = 4 years; uint256 public constant cliffAdvisorsTokens = 1 years; uint256 public constant lockAdvisorsTokens = 2 years; uint256 public constant futureRoundTokensRelease = 1 years; uint256 public constant presaleBonusLock = 90 days; uint256 public constant presaleParticipationMinimum = 10 ether; // 15% uint256 public constant dateTier2 = 1528761600; // Tuesday 12 June 2018 00:00:00 // 10% uint256 public constant dateTier3 = 1529366400; // Tuesday 19 June 2018 00:00:00 // 5% uint256 public constant dateTier4 = 1529971200; // Tuesday 26 June 2018 00:00:00 uint256 public baseEthCapPerAddress = 3 ether; mapping (address => address) public timelockedTokensContracts; mapping (address => bool) public whiteListedAddress; mapping (address => bool) public whiteListedAddressPresale; /** * @dev Creates the crowdsale. Set starting dates, ending date, caps and wallet. Set the date of presale bonus release. * @param _startDate start of the presale (EPOCH format) * @param _startGeneralSale start of the crowdsale (EPOCH format) * @param _endDate end of the crowdsale (EPOCH format) * @param _goal soft cap * @param _presaleCap hard cap of the presale * @param _cap global hard cap * @param _wallet address receiving ether if sale is successful **/ constructor(uint256 _startDate, uint256 _startGeneralSale, uint256 _endDate, uint256 _goal, uint256 _presaleCap, uint256 _cap, address _wallet) public CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(generalRate, _startDate, _endDate, _wallet) ProgressiveIndividualCappedCrowdsale(baseEthCapPerAddress, _startGeneralSale) { require(_goal <= _cap, "goal is superior to cap"); require(_startGeneralSale > _startDate, "general sale is starting before presale"); require(_endDate > _startGeneralSale, "sale ends before general start"); require(_presaleCap > 0, "presale cap is inferior or equal to 0"); require(_presaleCap <= _cap, "presale cap is superior to sale cap"); startGeneralSale = _startGeneralSale; presaleCap = _presaleCap; dateOfBonusRelease = endTime.add(presaleBonusLock); } /** * @dev Creates the talao token. * @return the TalaoToken address **/ function createTokenContract() internal returns (MintableToken) { return new TalaoToken(); } /** * @dev Checks if the sender is whitelisted for the presale. **/ modifier onlyPresaleWhitelisted() { require(isWhitelistedPresale(msg.sender), "address is not whitelisted for presale"); _; } /** * @dev Checks if the sender is whitelisted for the crowdsale. **/ modifier onlyWhitelisted() { require(isWhitelisted(msg.sender) || isWhitelistedPresale(msg.sender), "address is not whitelisted for sale"); _; } /** * @dev Whitelists an array of users for the crowdsale. * @param _users the users to be whitelisted */ function whitelistAddresses(address[] _users) public onlyOwner { for(uint i = 0 ; i < _users.length ; i++) { whiteListedAddress[_users[i]] = true; } } /** * @dev Removes a user from the crowdsale whitelist. * @param _user the user to be removed from the crowdsale whitelist */ function unwhitelistAddress(address _user) public onlyOwner { whiteListedAddress[_user] = false; } /** * @dev Whitelists a user for the presale with an individual cap ; cap needs to be above participation if set again * @param _user the users to be whitelisted * @param _cap the user individual cap in wei */ function whitelistAddressPresale(address _user, uint _cap) public onlyOwner { require(_cap > presaleParticipation[_user], "address has reached participation cap"); whiteListedAddressPresale[_user] = true; presaleIndividualCap[_user] = _cap; } /** * @dev Removes a user from the presale whitelist. * @param _user the user to be removed from the presale whitelist */ function unwhitelistAddressPresale(address _user) public onlyOwner { whiteListedAddressPresale[_user] = false; } /** * @dev Mints tokens corresponding to the transaction value for a whitelisted user during the crowdsale. * @param beneficiary the user wanting to buy tokens */ function buyTokens(address beneficiary) public payable onlyWhitelisted { require(beneficiary != 0x0, "beneficiary cannot be 0x0"); require(validPurchase(), "purchase is not valid"); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(generalRate); weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } /** * @dev Mints tokens corresponding to the transaction value for a whitelisted user during the presale. * Presale bonus is timelocked. * @param beneficiary the user wanting to buy tokens */ function buyTokensPresale(address beneficiary) public payable onlyPresaleWhitelisted { require(beneficiary != 0x0, "beneficiary cannot be 0x0"); require(validPurchasePresale(), "presale purchase is not valid"); // minting tokens at general rate because these tokens are not timelocked uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(generalRate); // checking if a timelock contract has been already created (not the first presale investment) // creating a timelock contract if none exists if(timelockedTokensContracts[beneficiary] == 0) { timelockedTokensContracts[beneficiary] = new TokenTimelock(token, beneficiary, dateOfBonusRelease); } // minting timelocked tokens ; balance goes to the timelock contract uint256 timelockedTokens = preSaleBonus(weiAmount); weiRaisedPreSale = weiRaisedPreSale.add(weiAmount); token.mint(beneficiary, tokens); token.mint(timelockedTokensContracts[beneficiary], timelockedTokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, (tokens.add(timelockedTokens))); forwardFunds(); } /** * @dev Overriding the finalization method to add minting for founders/team/reserve if soft cap is reached. * Also deploying the marketplace and transferring ownership to the crowdsale owner. */ function finalization() internal { if (goalReached()) { // advisors tokens : 3M ; 1 year cliff, vested for another year timelockedTokensContracts[advisorsWallet] = new TokenVesting(advisorsWallet, now, cliffAdvisorsTokens, lockAdvisorsTokens, false); // Vesting for founders ; not revocable ; 1 year cliff, vested for another year timelockedTokensContracts[foundersWallet1] = new TokenVesting(foundersWallet1, now, cliffTeamTokensRelease, lockTeamTokens, false); timelockedTokensContracts[foundersWallet2] = new TokenVesting(foundersWallet2, now, cliffTeamTokensRelease, lockTeamTokens, false); timelockedTokensContracts[foundersWallet3] = new TokenVesting(foundersWallet3, now, cliffTeamTokensRelease, lockTeamTokens, false); // mint remaining tokens out of 150M to be timelocked 1 year for future round(s) uint dateOfFutureRoundRelease = now.add(futureRoundTokensRelease); timelockedTokensContracts[futureRoundWallet] = new TokenTimelock(token, futureRoundWallet, dateOfFutureRoundRelease); token.mint(timelockedTokensContracts[advisorsWallet], 3000000000000000000000000); token.mint(timelockedTokensContracts[foundersWallet1], 4000000000000000000000000); token.mint(timelockedTokensContracts[foundersWallet2], 4000000000000000000000000); token.mint(timelockedTokensContracts[foundersWallet3], 4000000000000000000000000); // talao shareholders & employees token.mint(shareholdersWallet, 6000000000000000000000000); // tokens reserve for talent ambassador, bounty and cash reserve : 29M tokens ; no timelock token.mint(reserveWallet, 29000000000000000000000000); uint256 totalSupply = token.totalSupply(); uint256 maxSupply = 150000000000000000000000000; uint256 toMint = maxSupply.sub(totalSupply); token.mint(timelockedTokensContracts[futureRoundWallet], toMint); token.finishMinting(); // deploy the marketplace TalaoToken talao = TalaoToken(address(token)); TalaoMarketplace marketplace = new TalaoMarketplace(address(token)); talao.setMarketplace(address(marketplace)); marketplace.transferOwnership(owner); // give the token ownership to the crowdsale owner for vault purposes token.transferOwnership(owner); } // if soft cap not reached ; vault opens for refunds super.finalization(); } /** * @dev Fallback function redirecting to buying tokens functions depending on the time period. **/ function () external payable { if (now >= startTime && now < startGeneralSale){ buyTokensPresale(msg.sender); } else { buyTokens(msg.sender); } } /** * @dev Checks if the crowdsale purchase is valid: correct time, value and hard cap not reached. * Calls ProgressiveIndividualCappedCrowdsale's validPurchase to get individual cap. * @return true if all criterias are satisfied ; false otherwise **/ function validPurchase() internal returns (bool) { bool withinPeriod = now >= startGeneralSale && now <= endTime; bool nonZeroPurchase = msg.value != 0; uint256 totalWeiRaised = weiRaisedPreSale.add(weiRaised); bool withinCap = totalWeiRaised.add(msg.value) <= cap; return withinCap && withinPeriod && nonZeroPurchase && super.validPurchase(); } /** * @dev Checks if the presale purchase is valid: correct time, value and presale hard cap not reached. * @return true if all criterias are satisfied ; false otherwise **/ function validPurchasePresale() internal returns (bool) { presaleParticipation[msg.sender] = presaleParticipation[msg.sender].add(msg.value); bool enough = presaleParticipation[msg.sender] >= presaleParticipationMinimum; bool notTooMuch = presaleIndividualCap[msg.sender] >= presaleParticipation[msg.sender]; bool withinPeriod = now >= startTime && now < startGeneralSale; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaisedPreSale.add(msg.value) <= presaleCap; return withinPeriod && nonZeroPurchase && withinCap && enough && notTooMuch; } function preSaleBonus(uint amount) internal returns (uint) { if(now < dateTier2) { return amount.mul(presaleBonus); } else if (now < dateTier3) { return amount.mul(presaleBonusTier2); } else if (now < dateTier4) { return amount.mul(presaleBonusTier3); } else { return amount.mul(presaleBonusTier4); } } /** * @dev Override of the goalReached function in order to add presale weis to crowdsale weis and check if the total amount has reached the soft cap. * @return true if soft cap has been reached ; false otherwise **/ function goalReached() public constant returns (bool) { uint256 totalWeiRaised = weiRaisedPreSale.add(weiRaised); return totalWeiRaised >= goal || super.goalReached(); } /** * @dev Check if the user is whitelisted for the crowdsale. * @return true if user is whitelisted ; false otherwise **/ function isWhitelisted(address _user) public constant returns (bool) { return whiteListedAddress[_user]; } /** * @dev Check if the user is whitelisted for the presale. * @return true if user is whitelisted ; false otherwise **/ function isWhitelistedPresale(address _user) public constant returns (bool) { return whiteListedAddressPresale[_user]; } }
TOD1
pragma solidity 0.4.20; 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); } // ---------------------------------------------------------------------------- // VIOLET ERC20 Standard Token // ---------------------------------------------------------------------------- contract VLTToken is ERC20Interface { using SafeMath for uint256; address public owner = msg.sender; bytes32 public symbol; bytes32 public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function VLTToken() public { symbol = "VAI"; name = "VIOLET"; decimals = 18; _totalSupply = 250000000 * 10**uint256(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { // allow sending 0 tokens if (_value == 0) { Transfer(msg.sender, _to, _value); // Follow the spec to louch the event when transfer 0 return; } require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { // allow sending 0 tokens if (_value == 0) { Transfer(_from, _to, _value); // Follow the spec to louch the event when transfer 0 return; } require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } /** * 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) { require(_value <= balances[_from]); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowed allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance _totalSupply = _totalSupply.sub(_value); // Update totalSupply Burn(_from, _value); Transfer(_from, address(0), _value); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ViolaCrowdsale * @dev ViolaCrowdsale reserves token from supply when eth is received * funds will be forwarded after the end of crowdsale. Tokens will be claimable * within 7 days after crowdsale ends. */ contract ViolaCrowdsale is Ownable { using SafeMath for uint256; enum State { Deployed, PendingStart, Active, Paused, Ended, Completed } //Status of contract State public status = State.Deployed; // The token being sold VLTToken public violaToken; //For keeping track of whitelist address. cap >0 = whitelisted mapping(address=>uint) public maxBuyCap; //For checking if address passed KYC mapping(address => bool)public addressKYC; //Total wei sum an address has invested mapping(address=>uint) public investedSum; //Total violaToken an address is allocated mapping(address=>uint) public tokensAllocated; //Total violaToken an address purchased externally is allocated mapping(address=>uint) public externalTokensAllocated; //Total bonus violaToken an address is entitled after vesting mapping(address=>uint) public bonusTokensAllocated; //Total bonus violaToken an address purchased externally is entitled after vesting mapping(address=>uint) public externalBonusTokensAllocated; //Store addresses that has registered for crowdsale before (pushed via setWhitelist) //Does not mean whitelisted as it can be revoked. Just to track address for loop address[] public registeredAddress; //Total amount not approved for withdrawal uint256 public totalApprovedAmount = 0; //Start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public bonusVestingPeriod = 60 days; /** * Note all values are calculated in wei(uint256) including token amount * 1 ether = 1000000000000000000 wei * 1 viola = 1000000000000000000 vi lawei */ //Address where funds are collected address public wallet; //Min amount investor can purchase uint256 public minWeiToPurchase; // how many token units *in wei* a buyer gets *per wei* uint256 public rate; //Extra bonus token to give *in percentage* uint public bonusTokenRateLevelOne = 20; uint public bonusTokenRateLevelTwo = 15; uint public bonusTokenRateLevelThree = 10; uint public bonusTokenRateLevelFour = 0; //Total amount of tokens allocated for crowdsale uint256 public totalTokensAllocated; //Total amount of tokens reserved from external sources //Sub set of totalTokensAllocated ( totalTokensAllocated - totalReservedTokenAllocated = total tokens allocated for purchases using ether ) uint256 public totalReservedTokenAllocated; //Numbers of token left above 0 to still be considered sold uint256 public leftoverTokensBuffer; /** * event for front end logging */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 bonusAmount); event ExternalTokenPurchase(address indexed purchaser, uint256 amount, uint256 bonusAmount); event ExternalPurchaseRefunded(address indexed purchaser, uint256 amount, uint256 bonusAmount); event TokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event BonusTokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event TopupTokenAllocated(address indexed tokenReceiver, uint256 amount, uint256 bonusAmount); event CrowdsalePending(); event CrowdsaleStarted(); event CrowdsaleEnded(); event BonusRateChanged(); event Refunded(address indexed beneficiary, uint256 weiAmount); //Set inital arguments of the crowdsale function initialiseCrowdsale (uint256 _startTime, uint256 _rate, address _tokenAddress, address _wallet) onlyOwner external { require(status == State.Deployed); require(_startTime >= now); require(_rate > 0); require(address(_tokenAddress) != address(0)); require(_wallet != address(0)); startTime = _startTime; endTime = _startTime + 30 days; rate = _rate; wallet = _wallet; violaToken = VLTToken(_tokenAddress); status = State.PendingStart; CrowdsalePending(); } /** * Crowdsale state functions * To track state of current crowdsale */ // To be called by Ethereum alarm clock or anyone //Can only be called successfully when time is valid function startCrowdsale() external { require(withinPeriod()); require(violaToken != address(0)); require(getTokensLeft() > 0); require(status == State.PendingStart); status = State.Active; CrowdsaleStarted(); } //To be called by owner or contract //Ends the crowdsale when tokens are sold out function endCrowdsale() public { if (!tokensHasSoldOut()) { require(msg.sender == owner); } require(status == State.Active); bonusVestingPeriod = now + 60 days; status = State.Ended; CrowdsaleEnded(); } //Emergency pause function pauseCrowdsale() onlyOwner external { require(status == State.Active); status = State.Paused; } //Resume paused crowdsale function unpauseCrowdsale() onlyOwner external { require(status == State.Paused); status = State.Active; } function completeCrowdsale() onlyOwner external { require(hasEnded()); require(violaToken.allowance(owner, this) == 0); status = State.Completed; _forwardFunds(); assert(this.balance == 0); } function burnExtraTokens() onlyOwner external { require(hasEnded()); uint256 extraTokensToBurn = violaToken.allowance(owner, this); violaToken.burnFrom(owner, extraTokensToBurn); assert(violaToken.allowance(owner, this) == 0); } // send ether to the fund collection wallet function _forwardFunds() internal { wallet.transfer(this.balance); } function partialForwardFunds(uint _amountToTransfer) onlyOwner external { require(status == State.Ended); require(_amountToTransfer < totalApprovedAmount); totalApprovedAmount = totalApprovedAmount.sub(_amountToTransfer); wallet.transfer(_amountToTransfer); } /** * Setter functions for crowdsale parameters * Only owner can set values */ function setLeftoverTokensBuffer(uint256 _tokenBuffer) onlyOwner external { require(_tokenBuffer > 0); require(getTokensLeft() >= _tokenBuffer); leftoverTokensBuffer = _tokenBuffer; } //Set the ether to token rate function setRate(uint _rate) onlyOwner external { require(_rate > 0); rate = _rate; } function setBonusTokenRateLevelOne(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelOne = _rate; BonusRateChanged(); } function setBonusTokenRateLevelTwo(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelTwo = _rate; BonusRateChanged(); } function setBonusTokenRateLevelThree(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelThree = _rate; BonusRateChanged(); } function setBonusTokenRateLevelFour(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelFour = _rate; BonusRateChanged(); } function setMinWeiToPurchase(uint _minWeiToPurchase) onlyOwner external { minWeiToPurchase = _minWeiToPurchase; } /** * Whitelisting and KYC functions * Whitelisted address can buy tokens, KYC successful purchaser can claim token. Refund if fail KYC */ //Set the amount of wei an address can purchase up to //@dev Value of 0 = not whitelisted //@dev cap is in *18 decimals* ( 1 token = 1*10^18) function setWhitelistAddress( address _investor, uint _cap ) onlyOwner external { require(_cap > 0); require(_investor != address(0)); maxBuyCap[_investor] = _cap; registeredAddress.push(_investor); //add event } //Remove the address from whitelist function removeWhitelistAddress(address _investor) onlyOwner external { require(_investor != address(0)); maxBuyCap[_investor] = 0; uint256 weiAmount = investedSum[_investor]; if (weiAmount > 0) { _refund(_investor); } } //Flag address as KYC approved. Address is now approved to claim tokens function approveKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = true; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.add(weiAmount); } //Set KYC status as failed. Refund any eth back to address function revokeKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = false; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.sub(weiAmount); if (weiAmount > 0) { _refund(_kycAddress); } } /** * Getter functions for crowdsale parameters * Does not use gas */ //Checks if token has been sold out function tokensHasSoldOut() view internal returns (bool) { if (getTokensLeft() <= leftoverTokensBuffer) { return true; } else { return false; } } // @return true if the transaction can buy tokens function withinPeriod() public view returns (bool) { return now >= startTime && now <= endTime; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (status == State.Ended) { return true; } return now > endTime; } function getTokensLeft() public view returns (uint) { return violaToken.allowance(owner, this).sub(totalTokensAllocated); } function transferTokens (address receiver, uint tokenAmount) internal { require(violaToken.transferFrom(owner, receiver, tokenAmount)); } function getTimeBasedBonusRate() public view returns(uint) { bool bonusDuration1 = now >= startTime && now <= (startTime + 1 days); //First 24hr bool bonusDuration2 = now > (startTime + 1 days) && now <= (startTime + 3 days);//Next 48 hr bool bonusDuration3 = now > (startTime + 3 days) && now <= (startTime + 10 days);//4th to 10th day bool bonusDuration4 = now > (startTime + 10 days) && now <= endTime;//11th day onwards if (bonusDuration1) { return bonusTokenRateLevelOne; } else if (bonusDuration2) { return bonusTokenRateLevelTwo; } else if (bonusDuration3) { return bonusTokenRateLevelThree; } else if (bonusDuration4) { return bonusTokenRateLevelFour; } else { return 0; } } function getTotalTokensByAddress(address _investor) public view returns(uint) { return getTotalNormalTokensByAddress(_investor).add(getTotalBonusTokensByAddress(_investor)); } function getTotalNormalTokensByAddress(address _investor) public view returns(uint) { return tokensAllocated[_investor].add(externalTokensAllocated[_investor]); } function getTotalBonusTokensByAddress(address _investor) public view returns(uint) { return bonusTokensAllocated[_investor].add(externalBonusTokensAllocated[_investor]); } function _clearTotalNormalTokensByAddress(address _investor) internal { tokensAllocated[_investor] = 0; externalTokensAllocated[_investor] = 0; } function _clearTotalBonusTokensByAddress(address _investor) internal { bonusTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; } /** * Functions to handle buy tokens * Fallback function as entry point for eth */ // Called when ether is sent to contract function () external payable { buyTokens(msg.sender); } //Used to buy tokens function buyTokens(address investor) internal { require(status == State.Active); require(msg.value >= minWeiToPurchase); uint weiAmount = msg.value; checkCapAndRecord(investor,weiAmount); allocateToken(investor,weiAmount); } //Internal call to check max user cap function checkCapAndRecord(address investor, uint weiAmount) internal { uint remaindingCap = maxBuyCap[investor]; require(remaindingCap >= weiAmount); maxBuyCap[investor] = remaindingCap.sub(weiAmount); investedSum[investor] = investedSum[investor].add(weiAmount); } //Internal call to allocated tokens purchased function allocateToken(address investor, uint weiAmount) internal { // calculate token amount to be created uint tokens = weiAmount.mul(rate); uint bonusTokens = tokens.mul(getTimeBasedBonusRate()).div(100); uint tokensToAllocate = tokens.add(bonusTokens); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(tokensToAllocate); tokensAllocated[investor] = tokensAllocated[investor].add(tokens); bonusTokensAllocated[investor] = bonusTokensAllocated[investor].add(bonusTokens); if (tokensHasSoldOut()) { endCrowdsale(); } TokenPurchase(investor, weiAmount, tokens, bonusTokens); } /** * Functions for refunds & claim tokens * */ //Refund users in case of unsuccessful crowdsale function _refund(address _investor) internal { uint256 investedAmt = investedSum[_investor]; require(investedAmt > 0); uint totalInvestorTokens = tokensAllocated[_investor].add(bonusTokensAllocated[_investor]); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); } _clearAddressFromCrowdsale(_investor); _investor.transfer(investedAmt); Refunded(_investor, investedAmt); } //Partial refund users function refundPartial(address _investor, uint _refundAmt, uint _tokenAmt, uint _bonusTokenAmt) onlyOwner external { uint investedAmt = investedSum[_investor]; require(investedAmt > _refundAmt); require(tokensAllocated[_investor] > _tokenAmt); require(bonusTokensAllocated[_investor] > _bonusTokenAmt); investedSum[_investor] = investedSum[_investor].sub(_refundAmt); tokensAllocated[_investor] = tokensAllocated[_investor].sub(_tokenAmt); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].sub(_bonusTokenAmt); uint totalRefundTokens = _tokenAmt.add(_bonusTokenAmt); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalRefundTokens); } _investor.transfer(_refundAmt); Refunded(_investor, _refundAmt); } //Used by investor to claim token function claimTokens() external { require(hasEnded()); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver, tokensToClaim); } //Used by investor to claim bonus token function claimBonusTokens() external { require(hasEnded()); require(now >= bonusVestingPeriod); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver, tokensToClaim); } //Used by owner to distribute bonus token function distributeBonusTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); require(now >= bonusVestingPeriod); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver,tokensToClaim); } //Used by owner to distribute token function distributeICOTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver,tokensToClaim); } //For owner to reserve token for presale // function reserveTokens(uint _amount) onlyOwner external { // require(getTokensLeft() >= _amount); // totalTokensAllocated = totalTokensAllocated.add(_amount); // totalReservedTokenAllocated = totalReservedTokenAllocated.add(_amount); // } // //To distribute tokens not allocated by crowdsale contract // function distributePresaleTokens(address _tokenReceiver, uint _amount) onlyOwner external { // require(hasEnded()); // require(_tokenReceiver != address(0)); // require(_amount > 0); // violaToken.transferFrom(owner, _tokenReceiver, _amount); // TokenDistributed(_tokenReceiver,_amount); // } //For external purchases & pre-sale via btc/fiat function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(_amount > 0); uint256 totalTokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= totalTokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate); totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount); ExternalTokenPurchase(_investor, _amount, _bonusAmount); } function refundAllExternalPurchase(address _investor) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] > 0); uint externalTokens = externalTokensAllocated[_investor]; uint externalBonusTokens = externalBonusTokensAllocated[_investor]; externalTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; uint totalInvestorTokens = externalTokens.add(externalBonusTokens); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalInvestorTokens); totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); ExternalPurchaseRefunded(_investor,externalTokens,externalBonusTokens); } function refundExternalPurchase(address _investor, uint _amountToRefund, uint _bonusAmountToRefund) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] >= _amountToRefund); require(externalBonusTokensAllocated[_investor] >= _bonusAmountToRefund); uint totalTokensToRefund = _amountToRefund.add(_bonusAmountToRefund); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].sub(_amountToRefund); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].sub(_bonusAmountToRefund); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalTokensToRefund); totalTokensAllocated = totalTokensAllocated.sub(totalTokensToRefund); ExternalPurchaseRefunded(_investor,_amountToRefund,_bonusAmountToRefund); } function _clearAddressFromCrowdsale(address _investor) internal { tokensAllocated[_investor] = 0; bonusTokensAllocated[_investor] = 0; investedSum[_investor] = 0; maxBuyCap[_investor] = 0; } function allocateTopupToken(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(hasEnded()); require(_amount > 0); uint256 tokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(_amount); tokensAllocated[_investor] = tokensAllocated[_investor].add(_amount); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].add(_bonusAmount); TopupTokenAllocated(_investor, _amount, _bonusAmount); } //For cases where token are mistakenly sent / airdrops function emergencyERC20Drain( ERC20 token, uint amount ) external onlyOwner { require(status == State.Completed); token.transfer(owner,amount); } }
TOD1
pragma solidity ^0.4.13; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); } contract Payout { ERC20Basic HorseToken; address payoutPoolAddress; address owner; address dev; address devTokensVestingAddress; bool payoutPaused; bool payoutSetup; uint256 public payoutPoolAmount; mapping(address => bool) public hasClaimed; constructor() public { HorseToken = ERC20Basic(0x5B0751713b2527d7f002c0c4e2a37e1219610A6B); // Horse Token Address payoutPoolAddress = address(0xf783A81F046448c38f3c863885D9e99D10209779); // takeout pool dev = address(0x1F92771237Bd5eae04e91B4B6F1d1a78D41565a2); // dev wallet devTokensVestingAddress = address(0x44935883932b0260C6B1018Cf6436650BD52a257); // vesting contract owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } modifier isPayoutPaused { require(!payoutPaused); _; } modifier hasNotClaimed { require(!hasClaimed[msg.sender]); _; } modifier isPayoutSetup { require(payoutSetup); _; } function setupPayout() external payable { require(!payoutSetup); require(msg.sender == payoutPoolAddress); payoutPoolAmount = msg.value; payoutSetup = true; payoutPaused = true; } function getTokenBalance() public view returns (uint256) { if (msg.sender == dev) { return (HorseToken.balanceOf(devTokensVestingAddress)); } else { return (HorseToken.balanceOf(msg.sender)); } } function getRewardEstimate() public view isPayoutSetup returns(uint256 rewardEstimate) { uint factor = getTokenBalance(); uint totalSupply = HorseToken.totalSupply(); factor = factor*(10**18); // 18 decimal precision factor = (factor/(totalSupply)); rewardEstimate = (payoutPoolAmount*factor)/(10**18); // 18 decimal correction } function claim() external isPayoutPaused hasNotClaimed isPayoutSetup { uint rewardAmount = getRewardEstimate(); hasClaimed[msg.sender] = true; require(rewardAmount <= address(this).balance); msg.sender.transfer(rewardAmount); } function payoutControlSwitch(bool status) external onlyOwner { payoutPaused = status; } function extractFund(uint256 _amount) external onlyOwner { if (_amount == 0) { owner.transfer(address(this).balance); } else { require(_amount <= address(this).balance); owner.transfer(_amount); } } }
TOD1
pragma solidity ^0.4.19; contract ETH_QUIZ { function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>0.5 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract TokenSale is Ownable, CappedCrowdsale, FinalizableCrowdsale, Whitelist, Pausable { bool public initialized; uint[10] public rates; uint[10] public times; uint public noOfWaves; address public wallet; address public reserveWallet; uint public minContribution; uint public maxContribution; function TokenSale(uint _openingTime, uint _endTime, uint _rate, uint _hardCap, ERC20 _token, address _reserveWallet, uint _minContribution, uint _maxContribution) Crowdsale(_rate, _reserveWallet, _token) CappedCrowdsale(_hardCap) TimedCrowdsale(_openingTime, _endTime) { require(_token != address(0)); require(_reserveWallet !=address(0)); require(_maxContribution > 0); require(_minContribution > 0); reserveWallet = _reserveWallet; minContribution = _minContribution; maxContribution = _maxContribution; } function initRates(uint[] _rates, uint[] _times) external onlyOwner { require(now < openingTime); require(_rates.length == _times.length); require(_rates.length > 0); noOfWaves = _rates.length; for(uint8 i=0;i<_rates.length;i++) { rates[i] = _rates[i]; times[i] = _times[i]; } initialized = true; } function getCurrentRate() public view returns (uint256) { for(uint i=0;i<noOfWaves;i++) { if(now <= times[i]) { return rates[i]; } } return 0; } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint rate = getCurrentRate(); return _weiAmount.mul(rate); } function setWallet(address _wallet) onlyOwner public { wallet = _wallet; } function setReserveWallet(address _reserve) onlyOwner public { require(_reserve != address(0)); reserveWallet = _reserve; } function setMinContribution(uint _min) onlyOwner public { require(_min > 0); minContribution = _min; } function setMaxContribution(uint _max) onlyOwner public { require(_max > 0); maxContribution = _max; } function finalization() internal { require(wallet != address(0)); wallet.transfer(this.balance); token.transfer(reserveWallet, token.balanceOf(this)); super.finalization(); } function _forwardFunds() internal { //overridden to make the smart contracts hold funds and not the wallet } function withdrawFunds(uint value) onlyWhitelisted external { require(this.balance >= value); msg.sender.transfer(value); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) whenNotPaused internal { require(_weiAmount >= minContribution); require(_weiAmount <= maxContribution); super._preValidatePurchase(_beneficiary, _weiAmount); } }
TOD1
pragma solidity ^0.4.18; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // ERC20 token interface is implemented only partially. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract NamiCrowdSale { using SafeMath for uint256; /// NAC Broker Presale Token /// @dev Constructor function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; namiPresale = _namiPresale; } /*/ * Constants /*/ string public name = "Nami ICO"; string public symbol = "NAC"; uint public decimals = 18; bool public TRANSFERABLE = false; // default not transferable uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei); uint public binary = 0; /*/ * Token state /*/ enum Phase { Created, Running, Paused, Migrating, Migrated } Phase public currentPhase = Phase.Created; uint public totalSupply = 0; // amount of tokens already sold // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdrawn only to namimultisigwallet's address. address public namiMultiSigWallet; // nami presale contract address public namiPresale; // Crowdsale manager has exclusive priveleges to burn presale tokens. address public crowdsaleManager; // binary option address address public binaryAddress; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; modifier onlyCrowdsaleManager() { require(msg.sender == crowdsaleManager); _; } modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyTranferable() { require(TRANSFERABLE); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } /*/ * Events /*/ event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); event LogPhaseSwitch(Phase newPhase); // Log migrate token event LogMigrate(address _from, address _to, uint256 amount); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /*/ * Public functions /*/ /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } // Transfer the balance from owner's account to another account // only escrow can send token (to send token private sale) function transferForTeam(address _to, uint256 _value) public onlyEscrow { _transfer(msg.sender, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyTranferable { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyTranferable returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyTranferable returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } // allows transfer token function changeTransferable () public onlyEscrow { TRANSFERABLE = !TRANSFERABLE; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // change binary value function changeBinary(uint _binary) public onlyEscrow { binary = _binary; } // change binary address function changeBinaryAddress(address _binaryAddress) public onlyEscrow { require(_binaryAddress != 0x0); binaryAddress = _binaryAddress; } /* * price in ICO: * first week: 1 ETH = 2400 NAC * second week: 1 ETH = 23000 NAC * 3rd week: 1 ETH = 2200 NAC * 4th week: 1 ETH = 2100 NAC * 5th week: 1 ETH = 2000 NAC * 6th week: 1 ETH = 1900 NAC * 7th week: 1 ETH = 1800 NAC * 8th week: 1 ETH = 1700 nac * time: * 1517443200: Thursday, February 1, 2018 12:00:00 AM * 1518048000: Thursday, February 8, 2018 12:00:00 AM * 1518652800: Thursday, February 15, 2018 12:00:00 AM * 1519257600: Thursday, February 22, 2018 12:00:00 AM * 1519862400: Thursday, March 1, 2018 12:00:00 AM * 1520467200: Thursday, March 8, 2018 12:00:00 AM * 1521072000: Thursday, March 15, 2018 12:00:00 AM * 1521676800: Thursday, March 22, 2018 12:00:00 AM * 1522281600: Thursday, March 29, 2018 12:00:00 AM */ function getPrice() public view returns (uint price) { if (now < 1517443200) { // presale return 3450; } else if (1517443200 < now && now <= 1518048000) { // 1st week return 2400; } else if (1518048000 < now && now <= 1518652800) { // 2nd week return 2300; } else if (1518652800 < now && now <= 1519257600) { // 3rd week return 2200; } else if (1519257600 < now && now <= 1519862400) { // 4th week return 2100; } else if (1519862400 < now && now <= 1520467200) { // 5th week return 2000; } else if (1520467200 < now && now <= 1521072000) { // 6th week return 1900; } else if (1521072000 < now && now <= 1521676800) { // 7th week return 1800; } else if (1521676800 < now && now <= 1522281600) { // 8th week return 1700; } else { return binary; } } function() payable public { buy(msg.sender); } function buy(address _buyer) payable public { // Available only if presale is running. require(currentPhase == Phase.Running); // require ICO time or binary option require(now <= 1522281600 || msg.sender == binaryAddress); require(msg.value != 0); uint newTokens = msg.value * getPrice(); require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT); // add new token to buyer balanceOf[_buyer] = balanceOf[_buyer].add(newTokens); // add new token to totalSupply totalSupply = totalSupply.add(newTokens); LogBuy(_buyer,newTokens); Transfer(this,_buyer,newTokens); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function burnTokens(address _owner) public onlyCrowdsaleManager { // Available only during migration phase require(currentPhase == Phase.Migrating); uint tokens = balanceOf[_owner]; require(tokens != 0); balanceOf[_owner] = 0; totalSupply -= tokens; LogBurn(_owner, tokens); Transfer(_owner, crowdsaleManager, tokens); // Automatically switch phase when migration is done. if (totalSupply == 0) { currentPhase = Phase.Migrated; LogPhaseSwitch(Phase.Migrated); } } /*/ * Administrative functions /*/ function setPresalePhase(Phase _nextPhase) public onlyEscrow { bool canSwitchPhase = (currentPhase == Phase.Created && _nextPhase == Phase.Running) || (currentPhase == Phase.Running && _nextPhase == Phase.Paused) // switch to migration phase only if crowdsale manager is set || ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running) // switch to migrated only if everyting is migrated || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated && totalSupply == 0); require(canSwitchPhase); currentPhase = _nextPhase; LogPhaseSwitch(_nextPhase); } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } function setCrowdsaleManager(address _mgr) public onlyEscrow { // You can't change crowdsale contract when migration is in progress. require(currentPhase != Phase.Migrating); crowdsaleManager = _mgr; } // internal migrate migration tokens function _migrateToken(address _from, address _to) internal { PresaleToken presale = PresaleToken(namiPresale); uint256 newToken = presale.balanceOf(_from); require(newToken > 0); // burn old token presale.burnTokens(_from); // add new token to _to balanceOf[_to] = balanceOf[_to].add(newToken); // add new token to totalSupply totalSupply = totalSupply.add(newToken); LogMigrate(_from, _to, newToken); Transfer(this,_to,newToken); } // migate token function for Nami Team function migrateToken(address _from, address _to) public onlyEscrow { _migrateToken(_from, _to); } // migrate token for investor function migrateForInvestor() public { _migrateToken(msg.sender, msg.sender); } // Nami internal exchange // event for Nami exchange event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller); event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price); /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackExchange` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackExchange` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _price price to sell token. */ function transferToExchange(address _to, uint _value, uint _price) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackExchange(msg.sender, _value, _price); TransferToExchange(msg.sender, _to, _value, _price); } } /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackBuyer` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackBuyer` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _buyer address of seller. */ function transferToBuyer(address _to, uint _value, address _buyer) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackBuyer(msg.sender, _value, _buyer); TransferToBuyer(msg.sender, _to, _value, _buyer); } } //------------------------------------------------------------------------------------------------------- } /* * Binary option smart contract------------------------------- */ contract BinaryOption { /* * binary option controled by escrow to buy NAC with good price */ // NamiCrowdSale address address public namiCrowdSaleAddr; address public escrow; // namiMultiSigWallet address public namiMultiSigWallet; Session public session; uint public timeInvestInMinute = 30; uint public timeOneSession = 180; uint public sessionId = 1; uint public rate = 190; uint public constant MAX_INVESTOR = 20; uint public minimunEth = 10000000000000000; // minimunEth = 0.01 eth /** * Events for binany option system */ event SessionOpen(uint timeOpen, uint indexed sessionId); event InvestClose(uint timeInvestClose, uint priceOpen, uint indexed sessionId); event Invest(address indexed investor, bool choose, uint amount, uint timeInvest, uint indexed sessionId); event SessionClose(uint timeClose, uint indexed sessionId, uint priceClose, uint nacPrice, uint rate); event Deposit(address indexed sender, uint value); /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } // there is only one session available at one timeOpen // priceOpen is price of ETH in USD // priceClose is price of ETH in USD // process of one Session // 1st: escrow reset session by run resetSession() // 2nd: escrow open session by run openSession() => save timeOpen at this time // 3rd: all investor can invest by run invest(), send minimum 0.1 ETH // 4th: escrow close invest and insert price open for this Session // 5th: escrow close session and send NAC for investor struct Session { uint priceOpen; uint priceClose; uint timeOpen; bool isReset; bool isOpen; bool investOpen; uint investorCount; mapping(uint => address) investor; mapping(uint => bool) win; mapping(uint => uint) amountInvest; } function BinaryOption(address _namiCrowdSale, address _escrow, address _namiMultiSigWallet) public { require(_namiCrowdSale != 0x0 && _escrow != 0x0); namiCrowdSaleAddr = _namiCrowdSale; escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; } modifier onlyEscrow() { require(msg.sender==escrow); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // chagne minimunEth function changeMinEth(uint _minimunEth) public onlyEscrow { require(_minimunEth != 0); minimunEth = _minimunEth; } /// @dev Change time for investor can invest in one session, can only change at time not in session /// @param _timeInvest time invest in minutes function changeTimeInvest(uint _timeInvest) public onlyEscrow { require(!session.isOpen && _timeInvest < timeOneSession); timeInvestInMinute = _timeInvest; } // 100 < _rate < 200 // price of NAC for investor win = _rate/100 // price of NAC for investor loss = 2 - _rate/100 function changeRate(uint _rate) public onlyEscrow { require(100 < _rate && _rate < 200 && !session.isOpen); rate = _rate; } function changeTimeOneSession(uint _timeOneSession) public onlyEscrow { require(!session.isOpen && _timeOneSession > timeInvestInMinute); timeOneSession = _timeOneSession; } /// @dev withdraw ether to nami multisignature wallet, only escrow can call /// @param _amount value ether in wei to withdraw function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } /// @dev safe withdraw Ether to one of owner of nami multisignature wallet /// @param _withdraw address to withdraw function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } // @dev Returns list of owners. // @return List of owner addresses. // MAX_INVESTOR = 20 function getInvestors() public view returns (address[20]) { address[20] memory listInvestor; for (uint i = 0; i < MAX_INVESTOR; i++) { listInvestor[i] = session.investor[i]; } return listInvestor; } function getChooses() public view returns (bool[20]) { bool[20] memory listChooses; for (uint i = 0; i < MAX_INVESTOR; i++) { listChooses[i] = session.win[i]; } return listChooses; } function getAmount() public view returns (uint[20]) { uint[20] memory listAmount; for (uint i = 0; i < MAX_INVESTOR; i++) { listAmount[i] = session.amountInvest[i]; } return listAmount; } /// @dev reset all data of previous session, must run before open new session // only escrow can call function resetSession() public onlyEscrow { require(!session.isReset && !session.isOpen); session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.isOpen = false; session.investOpen = false; session.investorCount = 0; for (uint i = 0; i < MAX_INVESTOR; i++) { session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } } /// @dev Open new session, only escrow can call function openSession () public onlyEscrow { require(session.isReset && !session.isOpen); session.isReset = false; // open invest session.investOpen = true; session.timeOpen = now; session.isOpen = true; SessionOpen(now, sessionId); } /// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session /// @param _choose choise of investor, true is call, false is put function invest (bool _choose) public payable { require(msg.value >= minimunEth && session.investOpen); // msg.value >= 0.1 ether require(now < (session.timeOpen + timeInvestInMinute * 1 minutes)); require(session.investorCount < MAX_INVESTOR); session.investor[session.investorCount] = msg.sender; session.win[session.investorCount] = _choose; session.amountInvest[session.investorCount] = msg.value; session.investorCount += 1; Invest(msg.sender, _choose, msg.value, now, sessionId); } /// @dev close invest for escrow /// @param _priceOpen price ETH in USD function closeInvest (uint _priceOpen) public onlyEscrow { require(_priceOpen != 0 && session.investOpen); require(now > (session.timeOpen + timeInvestInMinute * 1 minutes)); session.investOpen = false; session.priceOpen = _priceOpen; InvestClose(now, _priceOpen, sessionId); } /// @dev get amount of ether to buy NAC for investor /// @param _ether amount ether which investor invest /// @param _rate rate between win and loss investor /// @param _status true for investor win and false for investor loss function getEtherToBuy (uint _ether, uint _rate, bool _status) public pure returns (uint) { if (_status) { return _ether * _rate / 100; } else { return _ether * (200 - _rate) / 100; } } /// @dev close session, only escrow can call /// @param _priceClose price of ETH in USD function closeSession (uint _priceClose) public onlyEscrow { require(_priceClose != 0 && now > (session.timeOpen + timeOneSession * 1 minutes)); require(!session.investOpen && session.isOpen); session.priceClose = _priceClose; bool result = (_priceClose>session.priceOpen)?true:false; uint etherToBuy; NamiCrowdSale namiContract = NamiCrowdSale(namiCrowdSaleAddr); uint price = namiContract.getPrice(); for (uint i = 0; i < session.investorCount; i++) { if (session.win[i]==result) { etherToBuy = getEtherToBuy(session.amountInvest[i], rate, true); } else { etherToBuy = getEtherToBuy(session.amountInvest[i], rate, false); } namiContract.buy.value(etherToBuy)(session.investor[i]); // reset investor session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } session.isOpen = false; SessionClose(now, sessionId, _priceClose, price, rate); sessionId += 1; // require(!session.isReset && !session.isOpen); // reset state session session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.investOpen = false; session.investorCount = 0; } } contract PresaleToken { mapping (address => uint256) public balanceOf; function burnTokens(address _owner) public; } /* * Contract that is working with ERC223 tokens */ /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public returns (bool success); function tokenFallbackBuyer(address _from, uint _value, address _buyer) public returns (bool success); function tokenFallbackExchange(address _from, uint _value, uint _price) public returns (bool success); } /* * Nami Internal Exchange smartcontract----------------------------------------------------------------- * */ contract NamiExchange { using SafeMath for uint; function NamiExchange(address _namiAddress) public { NamiAddr = _namiAddress; } event UpdateBid(address owner, uint price, uint balance); event UpdateAsk(address owner, uint price, uint volume); event BuyHistory(address indexed buyer, address indexed seller, uint price, uint volume, uint time); event SellHistory(address indexed seller, address indexed buyer, uint price, uint volume, uint time); mapping(address => OrderBid) public bid; mapping(address => OrderAsk) public ask; string public name = "NacExchange"; /// address of Nami token address public NamiAddr; /// price of Nac = ETH/NAC uint public price = 1; // struct store order of user struct OrderBid { uint price; uint eth; } struct OrderAsk { uint price; uint volume; } // prevent lost ether function() payable public { require(msg.data.length != 0); require(msg.value == 0); } modifier onlyNami { require(msg.sender == NamiAddr); _; } ///////////////// //---------------------------function about bid Order----------------------------------------------------------- function placeBuyOrder(uint _price) payable public { require(_price > 0 && msg.value > 0 && bid[msg.sender].eth == 0); if (msg.value > 0) { bid[msg.sender].eth = (bid[msg.sender].eth).add(msg.value); bid[msg.sender].price = _price; UpdateBid(msg.sender, _price, bid[msg.sender].eth); } } function tokenFallbackBuyer(address _from, uint _value, address _buyer) onlyNami public returns (bool success) { NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint ethOfBuyer = bid[_buyer].eth; uint maxToken = ethOfBuyer.mul(bid[_buyer].price); uint previousBalances = namiToken.balanceOf(_buyer); require(_value > 0 && ethOfBuyer != 0 && _buyer != 0x0); if (_value > maxToken) { if (_from.send(ethOfBuyer)) { uint previousBalances_2 = namiToken.balanceOf(_from); // transfer token namiToken.transfer(_buyer, maxToken); namiToken.transfer(_from, _value - maxToken); // update order bid[_buyer].eth = 0; UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); BuyHistory(_buyer, _from, bid[_buyer].price, maxToken, now); assert(previousBalances < namiToken.balanceOf(_buyer)); assert(previousBalances_2 < namiToken.balanceOf(_from)); return true; } else { // revert anything revert(); } } else { uint eth = _value.div(bid[_buyer].price); if (_from.send(eth)) { // transfer token namiToken.transfer(_buyer, _value); // update order bid[_buyer].eth = (bid[_buyer].eth).sub(eth); UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); BuyHistory(_buyer, _from, bid[_buyer].price, _value, now); assert(previousBalances < namiToken.balanceOf(_buyer)); return true; } else { // revert anything revert(); } } } function closeBidOrder() public { require(bid[msg.sender].eth > 0 && bid[msg.sender].price > 0); // transfer ETH msg.sender.transfer(bid[msg.sender].eth); // update order bid[msg.sender].eth = 0; UpdateBid(msg.sender, bid[msg.sender].price, bid[msg.sender].eth); } //////////////// //---------------------------function about ask Order----------------------------------------------------------- // place ask order by send NAC to Nami Exchange contract // this function place sell order function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) { require(_price > 0 && _value > 0 && ask[_from].volume == 0); if (_value > 0) { ask[_from].volume = (ask[_from].volume).add(_value); ask[_from].price = _price; UpdateAsk(_from, _price, ask[_from].volume); } return true; } function closeAskOrder() public { require(ask[msg.sender].volume > 0 && ask[msg.sender].price > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(msg.sender); // transfer token namiToken.transfer(msg.sender, ask[msg.sender].volume); // update order ask[msg.sender].volume = 0; UpdateAsk(msg.sender, ask[msg.sender].price, 0); // check balance assert(previousBalances < namiToken.balanceOf(msg.sender)); } function buyNac(address _seller) payable public returns (bool success) { require(msg.value > 0 && ask[_seller].volume > 0 && ask[_seller].price > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint maxEth = (ask[_seller].volume).div(ask[_seller].price); uint previousBalances = namiToken.balanceOf(msg.sender); if (msg.value > maxEth) { if (_seller.send(maxEth) && msg.sender.send(msg.value.sub(maxEth))) { // transfer token namiToken.transfer(msg.sender, ask[_seller].volume); SellHistory(_seller, msg.sender, ask[_seller].price, ask[_seller].volume, now); // update order ask[_seller].volume = 0; UpdateAsk(_seller, ask[_seller].price, 0); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } else { uint nac = (msg.value).mul(ask[_seller].price); if (_seller.send(msg.value)) { // transfer token namiToken.transfer(msg.sender, nac); // update order ask[_seller].volume = (ask[_seller].volume).sub(nac); UpdateAsk(_seller, ask[_seller].price, ask[_seller].volume); SellHistory(_seller, msg.sender, ask[_seller].price, nac, now); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } } } contract ERC23 { function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public returns (bool success); } /* * NamiMultiSigWallet smart contract------------------------------- */ /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. contract NamiMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function NamiMultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { // Transaction tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { Execution(transactionId); } else { ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } }
TOD1
pragma solidity ^0.4.25; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract IERC721 { 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; } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20BasicInterface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); uint8 public decimals; } contract Bussiness is Ownable { IERC721 public erc721Address = IERC721(0xdceaf1652a131f32a821468dc03a92df0edd86ea); ERC20BasicInterface public usdtToken = ERC20BasicInterface(0xdAC17F958D2ee523a2206206994597C13D831ec7); uint256 public ETHFee = 2; uint256 public HBWALLETFee = 1; uint256 public balance = address(this).balance; constructor() public {} struct Price { address tokenOwner; uint256 price; uint256 fee; } mapping(uint256 => Price) public prices; mapping(uint256 => Price) public usdtPrices; function ownerOf(uint256 _tokenId) public view returns (address){ return erc721Address.ownerOf(_tokenId); } function setPrice(uint256 _tokenId, uint256 _ethPrice, uint256 _usdtPrice) public { require(erc721Address.ownerOf(_tokenId) == msg.sender); prices[_tokenId] = Price(msg.sender, _ethPrice, 0); usdtPrices[_tokenId] = Price(msg.sender, _usdtPrice, 0); } function setPriceFeeEth(uint256 _tokenId, uint256 _ethPrice) public payable { require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice); uint256 ethfee; if(prices[_tokenId].price < _ethPrice) { ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / 100; require(msg.value == ethfee); ethfee += prices[_tokenId].fee; } else ethfee = _ethPrice * ETHFee / 100; prices[_tokenId] = Price(msg.sender, _ethPrice, ethfee); } function removePrice(uint256 tokenId) public returns (uint256){ require(erc721Address.ownerOf(tokenId) == msg.sender); if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee); resetPrice(tokenId); return prices[tokenId].price; } function getPrice(uint256 tokenId) public returns (address, address, uint256, uint256){ address currentOwner = erc721Address.ownerOf(tokenId); if(prices[tokenId].tokenOwner != currentOwner){ resetPrice(tokenId); } return (currentOwner, prices[tokenId].tokenOwner, prices[tokenId].price, usdtPrices[tokenId].price); } function setFee(uint256 _ethFee, uint256 _hbWalletFee) public view onlyOwner returns (uint256 ETHFee, uint256 HBWALLETFee){ require(_ethFee > 0 && _hbWalletFee > 0); ETHFee = _ethFee; HBWALLETFee = _hbWalletFee; return (ETHFee, HBWALLETFee); } /** * @dev Withdraw the amount of eth that is remaining in this contract. * @param _address The address of EOA that can receive token from this contract. */ function withdraw(address _address, uint256 amount) public onlyOwner { require(_address != address(0) && amount > 0 && address(this).balance > amount); _address.transfer(amount); } function buy(uint256 tokenId) public payable { require(erc721Address.getApproved(tokenId) == address(this)); require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value); erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId); prices[tokenId].tokenOwner.transfer(msg.value); resetPrice(tokenId); } function buyByUsdt(uint256 tokenId) public { require(usdtPrices[tokenId].price > 0 && erc721Address.getApproved(tokenId) == address(this)); require(usdtToken.transferFrom(msg.sender, usdtPrices[tokenId].tokenOwner, usdtPrices[tokenId].price)); erc721Address.transferFrom(usdtPrices[tokenId].tokenOwner, msg.sender, tokenId); resetPrice(tokenId); } function resetPrice(uint256 tokenId) private { prices[tokenId] = Price(address(0), 0, 0); usdtPrices[tokenId] = Price(address(0), 0, 0); } }
TOD1
pragma solidity ^0.4.0; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract MyFirstEthereumToken { // The keyword "public" makes those variables // readable from outside. address public owner; // Public variables of the token string public name = "MyFirstEthereumToken"; string public symbol = "MFET"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; uint256 public totalExtraTokens = 0; uint256 public totalContributed = 0; bool public onSale = false; /* This creates an array with all balances */ mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowance; // Events allow light clients to react on // changes efficiently. event Sent(address from, address to, uint amount); // 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); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); function name() public constant returns (string) { return name; } function symbol() public constant returns (string) { return symbol; } function decimals() public constant returns (uint8) { return decimals; } function totalSupply() public constant returns (uint256) { return totalSupply; } function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MyFirstEthereumToken(uint256 initialSupply) public payable { owner = msg.sender; // Update total supply with the decimal amount totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount //totalSupply = initialSupply; // Give the creator all initial tokens balances[msg.sender] = totalSupply; // Give the creator all initial tokens //balanceOf[msg.sender] = initialSupply; } /** * 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) { return _transfer(msg.sender, _to, _value); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal returns (bool success) { // mitigates the ERC20 short address attack //require(msg.data.length >= (2 * 32) + 4); // checks for minimum transfer amount require(_value > 0); // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Check for overflows // Save this for an assertion in the future uint previousBalances = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_to] += _value; // Call for Event Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); return true; } /** * Send tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function send(address _to, uint256 _value) public { _send(_to, _value); } /** * Internal send, only can be called by this contract */ function _send(address _to, uint256 _value) internal { address _from = msg.sender; // mitigates the ERC20 short address attack //require(msg.data.length >= (2 * 32) + 4); // checks for minimum transfer amount require(_value > 0); // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Check for overflows // Save this for an assertion in the future uint previousBalances = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_to] += _value; // Call for Event Sent(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on 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] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on 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 on 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; } } /** * Create tokens * * Create `_amount` tokens to `owner` account * * @param _amount the amount to create */ function createTokens(uint256 _amount) public { require(msg.sender == owner); //if (msg.sender != owner) return; balances[owner] += _amount; totalSupply += _amount; Transfer(0, owner, _amount); } /** * Withdraw funds * * Transfers the total amount of funds to ownwer account minus gas fee * */ function safeWithdrawAll() public returns (bool) { require(msg.sender == owner); uint256 _gasPrice = 30000000000; require(this.balance > _gasPrice); uint256 _totalAmount = this.balance - _gasPrice; owner.transfer(_totalAmount); return true; } /** * Withdraw funds * * Create `_amount` tokens to `owner` account * * @param _amount the amount to create */ function safeWithdraw(uint256 _amount) public returns (bool) { require(msg.sender == owner); uint256 _gasPrice = 30000000000; require(_amount > 0); uint256 totalAmount = _amount + _gasPrice; require(this.balance >= totalAmount); owner.transfer(totalAmount); return true; } function getBalanceContract() public constant returns(uint) { require(msg.sender == owner); return this.balance; } /** * 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(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply 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(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } // A function to buy tokens accesible by any address // The payable keyword allows the contract to accept ethers // from the transactor. The ethers to be deposited is entered as msg.value // (which will get clearer when we will call the functions in browser-solidity) // and the corresponding tokens are stored in balance[msg.sender] mapping. // underflows and overflows are security consideration which are // not checked in the process. But lets not worry about them for now. function buyTokens () public payable { // checks for minimum transfer amount require(msg.value > 0); require(onSale == true); owner.transfer(msg.value); totalContributed += msg.value; uint256 tokensAmount = msg.value * 1000; if(totalContributed >= 1 ether) { uint256 multiplier = (totalContributed / 1 ether); uint256 extraTokens = (tokensAmount * multiplier) / 10; totalExtraTokens += extraTokens; tokensAmount += extraTokens; } balances[msg.sender] += tokensAmount; totalSupply += tokensAmount; Transfer(address(this), msg.sender, tokensAmount); } /** * EnableSale Function * */ function enableSale() public { require(msg.sender == owner); onSale = true; } /** * DisableSale Function * */ function disableSale() public { require(msg.sender == owner); onSale = false; } /** * Kill Function * */ function kill() public { require(msg.sender == owner); onSale = false; selfdestruct(owner); } /** * Fallback Function * */ function() public payable { buyTokens(); //totalContributed += msg.value; } }
TOD1
pragma solidity ^0.4.20; contract PLAY_AND_GAIN { string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.17; /** * @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 add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, require mintingFinished before start transfers */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; bool public mintingFinished = false; mapping(address => uint256) releaseTime; // Only after finishMinting and checks for bounty accounts time restrictions modifier timeAllowed() { require(mintingFinished); require(now > releaseTime[msg.sender]); //finishSale + releasedays * 1 days _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public timeAllowed returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } // release time of freezed account function releaseAt(address _owner) public constant returns (uint256 date) { return releaseTime[_owner]; } // change restricted releaseXX account function changeReleaseAccount(address _owner, address _newowner) public returns (bool) { require(releaseTime[_owner] != 0 ); require(releaseTime[_newowner] == 0 ); balances[_newowner] = balances[_owner]; releaseTime[_newowner] = releaseTime[_owner]; balances[_owner] = 0; releaseTime[_owner] = 0; return true; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(mintingFinished); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public timeAllowed returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event UnMint(address indexed from, uint256 amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @param _releaseTime The (optional) freeze time for bounty accounts. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); if ( _releaseTime > 0 ) { releaseTime[_to] = _releaseTime; } Mint(_to, _amount); return true; } // drain tokens with refund function unMint(address _from) public onlyOwner returns (bool) { totalSupply = totalSupply.sub(balances[_from]); UnMint(_from, balances[_from]); balances[_from] = 0; return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract ArconaToken is MintableToken { string public constant name = "Arcona Distribution Contract"; string public constant symbol = "Arcona"; uint32 public constant decimals = 3; // 0.001 } contract Crowdsale is Ownable { using SafeMath for uint; address public multisig; address public restricted; address public registerbot; address public release6m; address public release12m; address public release18m; mapping (address => uint) public weiBalances; mapping (address => bool) registered; mapping (address => address) referral; mapping (string => address) certificate; uint restrictedPercent; uint refererPercent = 55; // 5.5% uint bonusPeriod = 10; // 10 days ArconaToken public token = new ArconaToken(); uint public startPreSale; uint public finishPreSale; uint public startSale; uint public finishSale; bool public isGlobalPause=false; uint public tokenTotal; uint public totalWeiSale=0; bool public isFinished=false; uint public hardcap; uint public softcap; uint public ratePreSale = 400*10**3; // 1ETH = 400 ARN uint public rateSale = 400*10**3; // 1ETH = 400 ARN function Crowdsale(uint256 _startPreSale,uint256 _finishPreSale,uint256 _startSale,uint256 _finishSale,address _multisig,address _restricted,address _registerbot, address _release6m, address _release12m, address _release18m) public { multisig = _multisig; restricted = _restricted; registerbot = _registerbot; release6m = _release6m; release12m = _release12m; release18m = _release18m; startSale=_startSale; finishSale=_finishSale; startPreSale=_startPreSale; finishPreSale=_finishPreSale; restrictedPercent = 40; hardcap = 135000*10**18; softcap = 2746*10**18; } modifier isRegistered() { require (registered[msg.sender]); _; } modifier preSaleIsOn() { require(now > startPreSale && now < finishPreSale && !isGlobalPause); _; } modifier saleIsOn() { require(now > startSale && now < finishSale && !isGlobalPause); _; } modifier anySaleIsOn() { require((now > startPreSale && now < finishPreSale && !isGlobalPause) || (now > startSale && now < finishSale && !isGlobalPause)); _; } modifier isUnderHardCap() { require(totalWeiSale <= hardcap); _; } function changeMultisig(address _new) public onlyOwner { multisig = _new; } function changeRegisterBot(address _new) public onlyOwner { registerbot = _new; } function changeRestricted(address _new) public onlyOwner { if (isFinished) { require(token.releaseAt(_new) == 0); token.changeReleaseAccount(restricted,_new); } restricted = _new; } function changeRelease6m(address _new) public onlyOwner { if (isFinished) { require(token.releaseAt(_new) == 0); token.changeReleaseAccount(release6m,_new); } release6m = _new; } function changeRelease12m(address _new) public onlyOwner { if (isFinished) { require(token.releaseAt(_new) == 0); token.changeReleaseAccount(release12m,_new); } release12m = _new; } function changeRelease18m(address _new) public onlyOwner { if (isFinished) { require(token.releaseAt(_new) == 0); token.changeReleaseAccount(release18m,_new); } release18m = _new; } function addCertificate(string _id, address _owner) public onlyOwner { require(certificate[_id] == address(0)); if (_owner != address(0)) { certificate[_id] = _owner; } else { certificate[_id] = owner; } } function editCertificate(string _id, address _newowner) public { require(certificate[_id] != address(0)); require(msg.sender == certificate[_id] || msg.sender == owner); certificate[_id] = _newowner; } function checkCertificate(string _id) public view returns (address) { return certificate[_id]; } function deleteCertificate(string _id) public onlyOwner { delete certificate[_id]; } function registerCustomer(address _customer, address _referral) public { require(msg.sender == registerbot || msg.sender == owner); require(_customer != address(0)); registered[_customer] = true; if (_referral != address(0) && _referral != _customer) { referral[_customer] = _referral; } } function checkCustomer(address _customer) public view returns (bool, address) { return ( registered[_customer], referral[_customer]); } function checkReleaseAt(address _owner) public constant returns (uint256 date) { return token.releaseAt(_owner); } function deleteCustomer(address _customer) public onlyOwner { require(_customer!= address(0)); delete registered[_customer]; delete referral[_customer]; // return Wei && Drain tokens token.unMint(_customer); if ( weiBalances[_customer] > 0 ) { _customer.transfer(weiBalances[_customer]); weiBalances[_customer] = 0; } } function globalPause(bool _state) public onlyOwner { isGlobalPause = _state; } function changeRateSale(uint _tokenAmount) public onlyOwner { require(isGlobalPause || (now > startSale && now < finishSale)); rateSale = _tokenAmount; } function changeRatePreSale(uint _tokenAmount) public onlyOwner { require(isGlobalPause || (now > startPreSale && now < finishPreSale)); ratePreSale = _tokenAmount; } function changeStartPreSale(uint256 _ts) public onlyOwner { startPreSale = _ts; } function changeFinishPreSale(uint256 _ts) public onlyOwner { finishPreSale = _ts; } function changeStartSale(uint256 _ts) public onlyOwner { startSale = _ts; } function changeFinishSale(uint256 _ts) public onlyOwner { finishSale = _ts; } function finishMinting() public onlyOwner { require(totalWeiSale >= softcap); require(!isFinished); multisig.transfer(this.balance); uint issuedTokenSupply = token.totalSupply(); // 40% restricted + 60% issuedTokenSupply = 100% uint restrictedTokens = issuedTokenSupply.mul(restrictedPercent).div(100 - restrictedPercent); issuedTokenSupply = issuedTokenSupply.add(restrictedTokens); // 13% - 11% for any purpose and 2% bounty token.mint(restricted, issuedTokenSupply.mul(13).div(100), now); // 27% - freezed founds to team & adwisers token.mint(release6m, issuedTokenSupply.mul(85).div(1000), now + 180 * 1 days); // 8.5 % token.mint(release12m, issuedTokenSupply.mul(85).div(1000), now + 365 * 1 days); // 8.5 % token.mint(release18m, issuedTokenSupply.mul(10).div(100), now + 545 * 1 days); // 10 % tokenTotal=token.totalSupply(); token.finishMinting(); isFinished=true; } function foreignBuyTest(uint256 _weiAmount, uint256 _rate) public pure returns (uint tokenAmount) { require(_weiAmount > 0); require(_rate > 0); return _rate.mul(_weiAmount).div(1 ether); } function foreignBuy(address _holder, uint256 _weiAmount, uint256 _rate) public isUnderHardCap preSaleIsOn onlyOwner { require(_weiAmount > 0); require(_rate > 0); registered[_holder] = true; uint tokens = _rate.mul(_weiAmount).div(1 ether); token.mint(_holder, tokens, 0); tokenTotal = token.totalSupply(); totalWeiSale = totalWeiSale.add(_weiAmount); } // Refund Either && Drain tokens function refund() public { require(totalWeiSale <= softcap && now >= finishSale); require(weiBalances[msg.sender] > 0); token.unMint(msg.sender); msg.sender.transfer(weiBalances[msg.sender]); totalWeiSale = totalWeiSale.sub(weiBalances[msg.sender]); tokenTotal = token.totalSupply(); weiBalances[msg.sender] = 0; } function buyTokensPreSale() public isRegistered isUnderHardCap preSaleIsOn payable { uint tokens = ratePreSale.mul(msg.value).div(1 ether); require(tokens >= 10000); // min 10 tokens multisig.transfer(msg.value); uint bonusValueTokens = 0; uint saleEther = (msg.value).mul(10).div(1 ether); if (saleEther >= 125 && saleEther < 375 ) { // 12,5 ETH bonusValueTokens = tokens.mul(15).div(100); } else if (saleEther >= 375 && saleEther < 750 ) { // 37,5 ETH bonusValueTokens = tokens.mul(20).div(100); } else if (saleEther >= 750 && saleEther < 1250 ) { // 75 ETH bonusValueTokens=tokens.mul(25).div(100); } else if (saleEther >= 1250 ) { // 125 ETH bonusValueTokens = tokens.mul(30).div(100); } tokens = tokens.add(bonusValueTokens); totalWeiSale = totalWeiSale.add(msg.value); token.mint(msg.sender, tokens, 0); if ( referral[msg.sender] != address(0) ) { uint refererTokens = tokens.mul(refererPercent).div(1000); token.mint(referral[msg.sender], refererTokens, 0); } tokenTotal=token.totalSupply(); } function createTokens() public isRegistered isUnderHardCap saleIsOn payable { uint tokens = rateSale.mul(msg.value).div(1 ether); require(tokens >= 10000); // min 10 tokens uint bonusTokens = 0; if ( now < startSale + (bonusPeriod * 1 days) ) { uint percent = bonusPeriod - (now - startSale).div(1 days); if ( percent > 0 ) { bonusTokens = tokens.mul(percent).div(100); } } tokens=tokens.add(bonusTokens); totalWeiSale = totalWeiSale.add(msg.value); token.mint(msg.sender, tokens, 0); if ( referral[msg.sender] != address(0) ) { uint refererTokens = tokens.mul(refererPercent).div(1000); token.mint(referral[msg.sender], refererTokens, 0); } tokenTotal=token.totalSupply(); weiBalances[msg.sender] = weiBalances[msg.sender].add(msg.value); } function createTokensAnySale() public isUnderHardCap anySaleIsOn payable { if ((now > startPreSale && now < finishPreSale) && !isGlobalPause) { buyTokensPreSale(); } else if ((now > startSale && now < finishSale) && !isGlobalPause) { createTokens(); } else { revert(); } } function() external anySaleIsOn isUnderHardCap payable { createTokensAnySale(); } }
TOD1
pragma solidity ^0.4.18; // ------------------------------------------------- // Assistive Reality ARX Token - ICO token sale contract // contact [email protected] for queries // Revision 20b // Refunds integrated, full test suite 20r passed // ------------------------------------------------- // ERC Token Standard #20 interface: // https://github.com/ethereum/EIPs/issues/20 // ------------------------------------------------ // 2018 improvements: // - Updates to comply with latest Solidity versioning (0.4.18): // - Classification of internal/private vs public functions // - Specification of pure functions such as SafeMath integrated functions // - Conversion of all constant to view or pure dependant on state changed // - Full regression test of code updates // - Revision of block number timing for new Ethereum block times // - Removed duplicate Buy/Transfer event call in buyARXtokens function (ethScan output verified) // - Burn event now records number of ARX tokens burned vs Refund event Eth // - Transfer event now fired when beneficiaryWallet withdraws // - Gas req optimisation for payable function to maximise compatibility // - Going live in code ahead of ICO announcement 09th March 2018 19:30 GMT // ------------------------------------------------- // Security reviews passed - cycle 20r // Functional reviews passed - cycle 20r // Final code revision and regression test cycle passed - cycle 20r // ------------------------------------------------- contract owned { address public owner; function owned() internal { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } contract safeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; safeAssert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { safeAssert(b > 0); uint256 c = a / b; safeAssert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { safeAssert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; safeAssert(c>=a && c>=b); return c; } function safeAssert(bool assertion) internal pure { if (!assertion) revert(); } } contract StandardToken is owned, safeMath { function balanceOf(address who) view public returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ARXCrowdsale is owned, safeMath { // owner/admin & token reward address public admin = owner; // admin address StandardToken public tokenReward; // address of the token used as reward // deployment variables for static supply sale uint256 private initialTokenSupply; uint256 private tokensRemaining; // multi-sig addresses and price variable address private beneficiaryWallet; // beneficiaryMultiSig (founder group) or wallet account // uint256 values for min,max,caps,tracking uint256 public amountRaisedInWei; // uint256 public fundingMinCapInWei; // uint256 public fundingMaxCapInWei; // // loop control, ICO startup and limiters string public CurrentStatus = ""; // current crowdsale status uint256 public fundingStartBlock; // crowdsale start block# uint256 public fundingEndBlock; // crowdsale end block# bool public isCrowdSaleClosed = false; // crowdsale completion boolean bool private areFundsReleasedToBeneficiary = false; // boolean for founder to receive Eth or not bool public isCrowdSaleSetup = false; // boolean for crowdsale setup event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Buy(address indexed _sender, uint256 _eth, uint256 _ARX); event Refund(address indexed _refunder, uint256 _value); event Burn(address _from, uint256 _value); mapping(address => uint256) balancesArray; mapping(address => uint256) usersARXfundValue; // default function, map admin function ARXCrowdsale() public onlyOwner { admin = msg.sender; CurrentStatus = "Crowdsale deployed to chain"; } // total number of tokens initially function initialARXSupply() public view returns (uint256 initialARXtokenCount) { return safeDiv(initialTokenSupply,1000000000000000000); // div by 1000000000000000000 for display normalisation (18 decimals) } // remaining number of tokens function remainingARXSupply() public view returns (uint256 remainingARXtokenCount) { return safeDiv(tokensRemaining,1000000000000000000); // div by 1000000000000000000 for display normalisation (18 decimals) } // setup the CrowdSale parameters function SetupCrowdsale(uint256 _fundingStartBlock, uint256 _fundingEndBlock) public onlyOwner returns (bytes32 response) { if ((msg.sender == admin) && (!(isCrowdSaleSetup)) && (!(beneficiaryWallet > 0))) { // init addresses beneficiaryWallet = 0x98DE47A1F7F96500276900925B334E4e54b1caD5; tokenReward = StandardToken(0xb0D926c1BC3d78064F3e1075D5bD9A24F35Ae6C5); // funding targets fundingMinCapInWei = 30000000000000000000; // 300 ETH wei initialTokenSupply = 277500000000000000000000000; // 277,500,000 + 18 dec resolution // update values amountRaisedInWei = 0; tokensRemaining = initialTokenSupply; fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; fundingMaxCapInWei = 4500000000000000000000; // configure crowdsale isCrowdSaleSetup = true; isCrowdSaleClosed = false; CurrentStatus = "Crowdsale is setup"; return "Crowdsale is setup"; } else if (msg.sender != admin) { return "not authorised"; } else { return "campaign cannot be changed"; } } function checkPrice() internal view returns (uint256 currentPriceValue) { if (block.number >= 5532293) { return (2250); } else if (block.number >= 5490292) { return (2500); } else if (block.number >= 5406291) { return (2750); } else if (block.number >= 5370290) { return (3000); } else if (block.number >= 5352289) { return (3250); } else if (block.number >= 5310289) { return (3500); } else if (block.number >= 5268288) { return (4000); } else if (block.number >= 5232287) { return (4500); } else if (block.number >= fundingStartBlock) { return (5000); } } // default payable function when sending ether to this contract function () public payable { // 0. conditions (length, crowdsale setup, zero check, exceed funding contrib check, contract valid check, within funding block range check, balance overflow check etc) require(!(msg.value == 0) && (msg.data.length == 0) && (block.number <= fundingEndBlock) && (block.number >= fundingStartBlock) && (tokensRemaining > 0)); // 1. vars uint256 rewardTransferAmount = 0; // 2. effects amountRaisedInWei = safeAdd(amountRaisedInWei, msg.value); rewardTransferAmount = (safeMul(msg.value, checkPrice())); // 3. interaction tokensRemaining = safeSub(tokensRemaining, rewardTransferAmount); tokenReward.transfer(msg.sender, rewardTransferAmount); // 4. events usersARXfundValue[msg.sender] = safeAdd(usersARXfundValue[msg.sender], msg.value); Buy(msg.sender, msg.value, rewardTransferAmount); } function beneficiaryMultiSigWithdraw(uint256 _amount) public onlyOwner { require(areFundsReleasedToBeneficiary && (amountRaisedInWei >= fundingMinCapInWei)); beneficiaryWallet.transfer(_amount); Transfer(this, beneficiaryWallet, _amount); } function checkGoalReached() public onlyOwner { // return crowdfund status to owner for each result case, update public vars // update state & status variables require (isCrowdSaleSetup); if ((amountRaisedInWei < fundingMinCapInWei) && (block.number <= fundingEndBlock && block.number >= fundingStartBlock)) { // ICO in progress, under softcap areFundsReleasedToBeneficiary = false; isCrowdSaleClosed = false; CurrentStatus = "In progress (Eth < Softcap)"; } else if ((amountRaisedInWei < fundingMinCapInWei) && (block.number < fundingStartBlock)) { // ICO has not started areFundsReleasedToBeneficiary = false; isCrowdSaleClosed = false; CurrentStatus = "Crowdsale is setup"; } else if ((amountRaisedInWei < fundingMinCapInWei) && (block.number > fundingEndBlock)) { // ICO ended, under softcap areFundsReleasedToBeneficiary = false; isCrowdSaleClosed = true; CurrentStatus = "Unsuccessful (Eth < Softcap)"; } else if ((amountRaisedInWei >= fundingMinCapInWei) && (tokensRemaining == 0)) { // ICO ended, all tokens bought! areFundsReleasedToBeneficiary = true; isCrowdSaleClosed = true; CurrentStatus = "Successful (ARX >= Hardcap)!"; } else if ((amountRaisedInWei >= fundingMinCapInWei) && (block.number > fundingEndBlock) && (tokensRemaining > 0)) { // ICO ended, over softcap! areFundsReleasedToBeneficiary = true; isCrowdSaleClosed = true; CurrentStatus = "Successful (Eth >= Softcap)!"; } else if ((amountRaisedInWei >= fundingMinCapInWei) && (tokensRemaining > 0) && (block.number <= fundingEndBlock)) { // ICO in progress, over softcap! areFundsReleasedToBeneficiary = true; isCrowdSaleClosed = false; CurrentStatus = "In progress (Eth >= Softcap)!"; } } function refund() public { // any contributor can call this to have their Eth returned. user's purchased ARX tokens are burned prior refund of Eth. //require minCap not reached require ((amountRaisedInWei < fundingMinCapInWei) && (isCrowdSaleClosed) && (block.number > fundingEndBlock) && (usersARXfundValue[msg.sender] > 0)); //burn user's token ARX token balance, refund Eth sent uint256 ethRefund = usersARXfundValue[msg.sender]; balancesArray[msg.sender] = 0; usersARXfundValue[msg.sender] = 0; //record Burn event with number of ARX tokens burned Burn(msg.sender, usersARXfundValue[msg.sender]); //send Eth back msg.sender.transfer(ethRefund); //record Refund event with number of Eth refunded in transaction Refund(msg.sender, ethRefund); } }
TOD1
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { 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; } } // Create Ad on DappVolume // Advertiser can choose 1 hour, 12 hours, 24 hours, or 1 week // half of the money gets sent back to last advertiser // // An investor can earn 10% of the ad revenue // Investors can get bought out by new investors // when an invester is bought out, they get 120% of their investment back contract dappVolumeAd { // import safemath using SafeMath for uint256; // set variables uint256 public dappId; uint256 public purchaseTimestamp; uint256 public purchaseSeconds; uint256 public investmentMin; uint256 public adPriceHour; uint256 public adPriceHalfDay; uint256 public adPriceDay; uint256 public adPriceWeek; uint256 public adPriceMultiple; address public contractOwner; address public lastOwner; address public theInvestor; // only contract owner modifier onlyContractOwner { require(msg.sender == contractOwner); _; } // set constructor constructor() public { investmentMin = 1000000000000000; adPriceHour = 5000000000000000; adPriceHalfDay = 50000000000000000; adPriceDay = 100000000000000000; adPriceWeek = 500000000000000000; adPriceMultiple = 1; contractOwner = msg.sender; theInvestor = contractOwner; lastOwner = contractOwner; } // withdraw funds to contract creator function withdraw() public onlyContractOwner { contractOwner.transfer(address(this).balance); } // set ad price multiple incase we want to up the price in the future function setAdPriceMultiple(uint256 amount) public onlyContractOwner { adPriceMultiple = amount; } // update and set ad function updateAd(uint256 id) public payable { // set minimum amount and make sure ad hasnt expired require(msg.value >= adPriceMultiple.mul(adPriceHour)); require(block.timestamp > purchaseTimestamp + purchaseSeconds); require(id > 0); // set ad time limit in seconds if (msg.value >= adPriceMultiple.mul(adPriceWeek)) { purchaseSeconds = 604800; // 1 week } else if (msg.value >= adPriceMultiple.mul(adPriceDay)) { purchaseSeconds = 86400; // 1 day } else if (msg.value >= adPriceMultiple.mul(adPriceHalfDay)) { purchaseSeconds = 43200; // 12 hours } else { purchaseSeconds = 3600; // 1 hour } // set new timestamp purchaseTimestamp = block.timestamp; // send 50% of the money to the last person lastOwner.transfer(msg.value.div(2)); // send 10% to the investor theInvestor.transfer(msg.value.div(10)); // set last owner lastOwner = msg.sender; // set dapp id dappId = id; } // update the investor function updateInvestor() public payable { require(msg.value >= investmentMin); theInvestor.transfer(msg.value.div(100).mul(60)); // send 60% to last investor (120% of original purchase) theInvestor = msg.sender; // set new investor investmentMin = investmentMin.mul(2); // double the price to become the investor } // get timestamp when ad ends function getPurchaseTimestampEnds() public view returns (uint _getPurchaseTimestampAdEnds) { return purchaseTimestamp.add(purchaseSeconds); } // get contract balance function getBalance() public view returns(uint256){ return address(this).balance; } }
TOD1
pragma solidity ^0.4.23; contract CoinJzc // @eachvar { // ======== 初始化代币相关逻辑 ============== // 地址信息 address public admin_address = 0x59a6C9d93838E1901990b50469d5126C720716dc; // @eachvar address public account_address = 0x59a6C9d93838E1901990b50469d5126C720716dc; // @eachvar 初始化后转入代币的地址 // 定义账户余额 mapping(address => uint256) balances; // solidity 会自动为 public 变量添加方法,有了下边这些变量,就能获得代币的基本信息了 string public name = "DaJinZhuCoin"; // @eachvar string public symbol = "JZC"; // @eachvar uint8 public decimals = 18; // @eachvar uint256 initSupply = 200000000; // @eachvar uint256 public totalSupply = 0; // @eachvar // 生成代币,并转入到 account_address 地址 constructor() payable public { totalSupply = mul(initSupply, 10**uint256(decimals)); balances[account_address] = totalSupply; } function balanceOf( address _addr ) public view returns ( uint ) { return balances[_addr]; } // ========== 转账相关逻辑 ==================== event Transfer( address indexed from, address indexed to, uint256 value ); function transfer( address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = sub(balances[msg.sender],_value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } // ========= 授权转账相关逻辑 ============= mapping (address => mapping (address => uint256)) internal allowed; event Approval( address indexed owner, address indexed spender, uint256 value ); function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = sub(balances[_from], _value); balances[_to] = add(balances[_to], _value); allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } function approve( address _spender, uint256 _value ) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = add(allowed[msg.sender][_spender], _addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = sub(oldValue, _subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ========= 直投相关逻辑 =============== bool public direct_drop_switch = true; // 是否开启直投 @eachvar uint256 public direct_drop_rate = 1000; // 兑换比例,注意这里是eth为单位,需要换算到wei @eachvar address public direct_drop_address = 0x59a6C9d93838E1901990b50469d5126C720716dc; // 用于发放直投代币的账户 @eachvar address public direct_drop_withdraw_address = 0x59a6C9d93838E1901990b50469d5126C720716dc; // 直投提现地址 @eachvar bool public direct_drop_range = false; // 是否启用直投有效期 @eachvar uint256 public direct_drop_range_start = 1547947620; // 有效期开始 @eachvar uint256 public direct_drop_range_end = 1579483620; // 有效期结束 @eachvar event TokenPurchase ( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); // 支持为别人购买 function buyTokens( address _beneficiary ) public payable // 接收支付 returns (bool) { require(direct_drop_switch); require(_beneficiary != address(0)); // 检查有效期开关 if( direct_drop_range ) { // 当前时间必须在有效期内 // solium-disable-next-line security/no-block-members require(block.timestamp >= direct_drop_range_start && block.timestamp <= direct_drop_range_end); } // 计算根据兑换比例,应该转移的代币数量 // uint256 tokenAmount = mul(div(msg.value, 10**18), direct_drop_rate); uint256 tokenAmount = div(mul(msg.value,direct_drop_rate ), 10**18); //此处用 18次方,这是 wei to ether 的换算,不是代币的,所以不用 decimals,先乘后除,否则可能为零 uint256 decimalsAmount = mul( 10**uint256(decimals), tokenAmount); // 首先检查代币发放账户余额 require ( balances[direct_drop_address] >= decimalsAmount ); assert ( decimalsAmount > 0 ); // 然后开始转账 uint256 all = add(balances[direct_drop_address], balances[_beneficiary]); balances[direct_drop_address] = sub(balances[direct_drop_address], decimalsAmount); balances[_beneficiary] = add(balances[_beneficiary], decimalsAmount); assert ( all == add(balances[direct_drop_address], balances[_beneficiary]) ); // 发送事件 emit TokenPurchase ( msg.sender, _beneficiary, msg.value, tokenAmount ); return true; } // ============== admin 相关函数 ================== modifier admin_only() { require(msg.sender==admin_address); _; } function setAdmin( address new_admin_address ) public admin_only returns (bool) { require(new_admin_address != address(0)); admin_address = new_admin_address; return true; } // 直投管理 function setDirectDrop( bool status ) public admin_only returns (bool) { direct_drop_switch = status; return true; } // ETH提现 function withDraw() public { // 管理员和之前设定的提现账号可以发起提现,但钱一定是进提现账号 require(msg.sender == admin_address || msg.sender == direct_drop_withdraw_address); require(address(this).balance > 0); // 全部转到直投提现中 direct_drop_withdraw_address.transfer(address(this).balance); } // ====================================== /// 默认函数 function () external payable { buyTokens(msg.sender); } // ========== 公用函数 =============== // 主要就是 safemath function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
TOD1
pragma solidity ^0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". **/ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. **/ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. **/ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. **/ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic interface * @dev Basic ERC20 interface **/ contract ERC20Basic { // function totalSupply() public view returns (uint256); function balanceOf(address _who) view public returns (uint); function transfer(address _to, uint _value) public returns (bool); // event Transfer(address indexed _from, address indexed _to, uint _value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 **/ contract ERC20 is ERC20Basic { // function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); // event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. **/ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 _totalSupply=0; /** * @dev total number of tokens in existence **/ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); // emit Transfer(msg.sender, _to, _value); // return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. **/ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { enum StackingStatus{ locked, unlocked } StackingStatus public stackingStatus=StackingStatus.unlocked; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(stackingStatus==StackingStatus.unlocked); require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); // balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // emit Transfer(_from, _to, _value); // return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } event Burn(address indexed burner, uint256 value); } /** * @title Configurable * @dev Configurable varriables of the contract **/ contract Configurable { uint256 constant percentDivider = 100000; uint256 constant cap = 2000000000*10**18; //2 billion uint256 internal tokensSold = 0; uint256 internal remainingTokens = 0; } /** * @title CrowdsaleToken * @dev Contract to preform crowd sale with token **/ contract CrowdsaleToken is StandardToken, Configurable, Ownable { enum DepositStatus{ locked, unlocked } /** * @dev Variables **/ DepositStatus public depositStatus=DepositStatus.locked; /** * @dev Events **/ event Logger(string _label, uint256 _note1, uint256 _note2, uint256 _note3, uint256 _note4); /** * @dev Mapping **/ /** * @dev constructor of CrowdsaleToken **/ constructor() public { // depositStatus = DepositStatus.locked; // remainingTokens = cap; } /* payments */ /** * @dev fallback function to send ether to for Crowd sale **/ function () external payable { require(depositStatus == DepositStatus.unlocked); require(msg.value > 0); } /** * @dev process buy tokens **/ function BuyToken(uint256 _amount) public onlyOwner { require(_amount>0 && _amount<=remainingTokens); tokensSold = tokensSold.add(_amount); // Increment raised amount remainingTokens = remainingTokens.sub(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); //emit Transfer(address(this), msg.sender, _amount); _totalSupply = _totalSupply.add(_amount); } function SellToken(uint256 _amount) public onlyOwner { require(_amount>0 && _amount<=_totalSupply ); tokensSold = tokensSold.sub(_amount); //decrement raised amount remainingTokens = remainingTokens.add(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); //emit Transfer(address(this), msg.sender, _amount); _totalSupply = _totalSupply.sub(_amount); } /* administrative functions */ /** lock/unlock deposit ETH **/ function lockDeposit() public onlyOwner{ require(depositStatus==DepositStatus.unlocked); depositStatus=DepositStatus.locked; } function unlockDeposit() public onlyOwner{ require(depositStatus==DepositStatus.locked); depositStatus=DepositStatus.unlocked; } /** lock/unlock stacking **/ function lockStacking() public onlyOwner{ require(stackingStatus==StackingStatus.unlocked); stackingStatus=StackingStatus.locked; } function unlockStacking() public onlyOwner{ require(stackingStatus==StackingStatus.locked); stackingStatus=StackingStatus.unlocked; } /** * @dev finalizeIco closes down the ICO and sets needed varriables **/ function finalizeIco() public onlyOwner { // Transfer any remaining tokens if(remainingTokens > 0) balances[owner] = balances[owner].add(remainingTokens); // transfer any remaining ETH balance in the contract to the owner owner.transfer(address(this).balance); } /** * @dev withdraw **/ function withdraw(address _address, uint256 _value) public onlyOwner { require(_address != address(0)); require(_value < address(this).balance); // _address.transfer(_value); } /** * @dev issues **/ function issues(address _address, uint256 _tokens) public onlyOwner { require(_tokens <= remainingTokens); // remainingTokens = remainingTokens.sub(_tokens); balances[_address] = balances[_address].add(_tokens); emit Transfer(address(this), _address, _tokens); _totalSupply = _totalSupply.add(_tokens); } function reduceTotalSupply(uint256 _amount) public onlyOwner { require(_amount > 0 && _amount < _totalSupply); _totalSupply -=_amount; } function plusTotalSupply(uint256 _amount) public onlyOwner { require(_amount > 0 && (_amount + _totalSupply)<= cap ); _totalSupply +=_amount; } /* public functions */ /** * @dev get max total supply **/ function getMaxTotalSupply() public pure returns(uint256) { return cap; } /** * @dev get total tokens sold **/ function getTotalSold() public view returns(uint256) { return tokensSold; } /** * @dev get total tokens sold **/ function getTotalRemaining() public view returns(uint256) { return remainingTokens; } function BurnToken(uint256 _amount) public onlyOwner{ require(_amount>0); require(_amount<= balances[msg.sender]); _totalSupply=_totalSupply.sub(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } } /** * @title ALS * @dev Contract to create the ALS Token **/ contract ALS is CrowdsaleToken { string public constant name = "ALS Token"; string public constant symbol = "ALS"; uint32 public constant decimals = 18; }
TOD1
/** * @title TEND token * @version 2.0 * @author Validity Labs AG <[email protected]> * * The TTA tokens are issued as participation certificates and represent * uncertificated securities within the meaning of article 973c Swiss CO. The * issuance of the TTA tokens has been governed by a prospectus issued by * Tend Technologies AG. * * TTA tokens are only recognized and transferable in undivided units. * * The holder of a TTA token must prove his possessorship to be recognized by * the issuer as being entitled to the rights arising out of the respective * participation certificate; he/she waives any rights if he/she is not in a * position to prove him/her being the holder of the respective token. * * Similarly, only the person who proves him/her being the holder of the TTA * Token is entitled to transfer title and ownership on the token to another * person. Both the transferor and the transferee agree and accept hereby * explicitly that the tokens are transferred digitally, i.e. in a form-free * manner. However, if any regulators, courts or similar would require written * confirmation of a transfer of the transferable uncertificated securities * from one investor to another investor, such investors will provide written * evidence of such transfer. */ pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract DividendToken is StandardToken, Ownable { using SafeMath for uint256; // time before dividendEndTime during which dividend cannot be claimed by token holders // instead the unclaimed dividend can be claimed by treasury in that time span uint256 public claimTimeout = 20 days; uint256 public dividendCycleTime = 350 days; uint256 public currentDividend; mapping(address => uint256) unclaimedDividend; // tracks when the dividend balance has been updated last time mapping(address => uint256) public lastUpdate; uint256 public lastDividendIncreaseDate; // allow payment of dividend only by special treasury account (treasury can be set and altered by owner, // multiple treasurer accounts are possible mapping(address => bool) public isTreasurer; uint256 public dividendEndTime = 0; event Payin(address _owner, uint256 _value, uint256 _endTime); event Payout(address _tokenHolder, uint256 _value); event Reclaimed(uint256 remainingBalance, uint256 _endTime, uint256 _now); event ChangedTreasurer(address treasurer, bool active); /** * @dev Deploy the DividendToken contract and set the owner of the contract */ constructor() public { isTreasurer[owner] = true; } /** * @dev Request payout dividend (claim) (requested by tokenHolder -> pull) * dividends that have not been claimed within 330 days expire and cannot be claimed anymore by the token holder. */ function claimDividend() public returns (bool) { // unclaimed dividend fractions should expire after 330 days and the owner can reclaim that fraction require(dividendEndTime > 0); require(dividendEndTime.sub(claimTimeout) > block.timestamp); updateDividend(msg.sender); uint256 payment = unclaimedDividend[msg.sender]; unclaimedDividend[msg.sender] = 0; msg.sender.transfer(payment); // Trigger payout event emit Payout(msg.sender, payment); return true; } /** * @dev Transfer dividend (fraction) to new token holder * @param _from address The address of the old token holder * @param _to address The address of the new token holder * @param _value uint256 Number of tokens to transfer */ function transferDividend(address _from, address _to, uint256 _value) internal { updateDividend(_from); updateDividend(_to); uint256 transAmount = unclaimedDividend[_from].mul(_value).div(balanceOf(_from)); unclaimedDividend[_from] = unclaimedDividend[_from].sub(transAmount); unclaimedDividend[_to] = unclaimedDividend[_to].add(transAmount); } /** * @dev Update the dividend of hodler * @param _hodler address The Address of the hodler */ function updateDividend(address _hodler) internal { // last update in previous period -> reset claimable dividend if (lastUpdate[_hodler] < lastDividendIncreaseDate) { unclaimedDividend[_hodler] = calcDividend(_hodler, totalSupply_); lastUpdate[_hodler] = block.timestamp; } } /** * @dev Get claimable dividend for the hodler * @param _hodler address The Address of the hodler */ function getClaimableDividend(address _hodler) public constant returns (uint256 claimableDividend) { if (lastUpdate[_hodler] < lastDividendIncreaseDate) { return calcDividend(_hodler, totalSupply_); } else { return (unclaimedDividend[_hodler]); } } /** * @dev Overrides transfer method from BasicToken * transfer token for a specified address * @param _to address The address to transfer to. * @param _value uint256 The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { transferDividend(msg.sender, _to, _value); // Return from inherited transfer method return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { // Prevent dividend to be claimed twice transferDividend(_from, _to, _value); // Return from inherited transferFrom method return super.transferFrom(_from, _to, _value); } /** * @dev Set / alter treasurer "account". This can be done from owner only * @param _treasurer address Address of the treasurer to create/alter * @param _active bool Flag that shows if the treasurer account is active */ function setTreasurer(address _treasurer, bool _active) public onlyOwner { isTreasurer[_treasurer] = _active; emit ChangedTreasurer(_treasurer, _active); } /** * @dev Request unclaimed ETH, payback to beneficiary (owner) wallet * dividend payment is possible every 330 days at the earliest - can be later, this allows for some flexibility, * e.g. board meeting had to happen a bit earlier this year than previous year. */ function requestUnclaimed() public onlyOwner { // Send remaining ETH to beneficiary (back to owner) if dividend round is over require(block.timestamp >= dividendEndTime.sub(claimTimeout)); msg.sender.transfer(address(this).balance); emit Reclaimed(address(this).balance, dividendEndTime, block.timestamp); } /** * @dev ETH Payin for Treasurer * Only owner or treasurer can do a payin for all token holder. * Owner / treasurer can also increase dividend by calling fallback function multiple times. */ function() public payable { require(isTreasurer[msg.sender]); require(dividendEndTime < block.timestamp); // pay back unclaimed dividend that might not have been claimed by owner yet if (address(this).balance > msg.value) { uint256 payout = address(this).balance.sub(msg.value); owner.transfer(payout); emit Reclaimed(payout, dividendEndTime, block.timestamp); } currentDividend = address(this).balance; // No active dividend cycle found, initialize new round dividendEndTime = block.timestamp.add(dividendCycleTime); // Trigger payin event emit Payin(msg.sender, msg.value, dividendEndTime); lastDividendIncreaseDate = block.timestamp; } /** * @dev calculate the dividend * @param _hodler address * @param _totalSupply uint256 */ function calcDividend(address _hodler, uint256 _totalSupply) public view returns(uint256) { return (currentDividend.mul(balanceOf(_hodler))).div(_totalSupply); } } contract TendToken is MintableToken, PausableToken, DividendToken { using SafeMath for uint256; string public constant name = "Tend Token"; string public constant symbol = "TTA"; uint8 public constant decimals = 18; // Minimum transferable chunk uint256 public granularity = 1e18; /** * @dev Constructor of TendToken that instantiate a new DividendToken */ constructor() public DividendToken() { // token should not be transferrable until after all tokens have been issued paused = true; } /** * @dev Internal function that ensures `_amount` is multiple of the granularity * @param _amount The quantity that wants to be checked */ function requireMultiple(uint256 _amount) internal view { require(_amount.div(granularity).mul(granularity) == _amount); } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { requireMultiple(_value); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { requireMultiple(_value); return super.transferFrom(_from, _to, _value); } /** * @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) { requireMultiple(_amount); // Return from inherited mint method return super.mint(_to, _amount); } /** * @dev Function to batch mint tokens * @param _to An array of addresses that will receive the minted tokens. * @param _amount An array with the amounts of tokens each address will get minted. * @return A boolean that indicates whether the operation was successful. */ function batchMint( address[] _to, uint256[] _amount ) hasMintPermission canMint public returns (bool) { require(_to.length == _amount.length); for (uint i = 0; i < _to.length; i++) { requireMultiple(_amount[i]); require(mint(_to[i], _amount[i])); } return true; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } contract RoundedTokenVesting is TokenVesting { using SafeMath for uint256; // Minimum transferable chunk uint256 public granularity; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, uint256 _granularity ) public TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable) { granularity = _granularity; } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { uint256 notRounded = totalBalance.mul(block.timestamp.sub(start)).div(duration); // Round down to the nearest token chunk by using integer division: (x / 1e18) * 1e18 uint256 rounded = notRounded.div(granularity).mul(granularity); return rounded; } } } contract TendTokenVested is TendToken { using SafeMath for uint256; /*** CONSTANTS ***/ uint256 public constant DEVELOPMENT_TEAM_CAP = 2e6 * 1e18; // 2 million * 1e18 uint256 public constant VESTING_CLIFF = 0 days; uint256 public constant VESTING_DURATION = 3 * 365 days; uint256 public developmentTeamTokensMinted; // for convenience we store vesting wallets address[] public vestingWallets; modifier onlyNoneZero(address _to, uint256 _amount) { require(_to != address(0)); require(_amount > 0); _; } /** * @dev allows contract owner to mint team tokens per DEVELOPMENT_TEAM_CAP and transfer to the development team's wallet (yes vesting) * @param _to address for beneficiary * @param _tokens uint256 token amount to mint */ function mintDevelopmentTeamTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) returns (bool) { requireMultiple(_tokens); require(developmentTeamTokensMinted.add(_tokens) <= DEVELOPMENT_TEAM_CAP); developmentTeamTokensMinted = developmentTeamTokensMinted.add(_tokens); RoundedTokenVesting newVault = new RoundedTokenVesting(_to, block.timestamp, VESTING_CLIFF, VESTING_DURATION, false, granularity); vestingWallets.push(address(newVault)); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan return mint(address(newVault), _tokens); } /** * @dev returns number of elements in the vestinWallets array */ function getVestingWalletLength() public view returns (uint256) { return vestingWallets.length; } }
TOD1
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/payment/Escrow.sol /** * @title Escrow * @dev Base escrow contract, holds funds destinated to a payee until they * withdraw them. The contract that uses the escrow as its payment method * should be its owner, and provide public methods redirecting to the escrow's * deposit and withdraw. */ contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } // File: openzeppelin-solidity/contracts/payment/ConditionalEscrow.sol /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param _payee The destination address of the funds. */ function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } // File: openzeppelin-solidity/contracts/payment/RefundEscrow.sol /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool) { return state == State.Refunding; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File: contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; // Amount tokens Sold uint256 public tokensSold; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); _preValidatePurchase(_beneficiary, weiAmount, tokens); // update state weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokens); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount, tokens); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount, tokens); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(_beneficiary, _weiAmount); * require(weiRaised.add(_weiAmount) <= cap); * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase * @param _tokenAmount Value in token involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase * @param _tokenAmount Value in token involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase * @param _tokenAmount Value in token involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime > _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed * @param _tokenAmount Amount of token purchased */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount); } } // File: contracts/crowdsale/validation/MilestoneCrowdsale.sol /** * @title MilestoneCrowdsale * @dev Crowdsale with multiple milestones separated by time and cap * @author Nikola Wyatt <[email protected]> */ contract MilestoneCrowdsale is TimedCrowdsale { using SafeMath for uint256; uint256 public constant MAX_MILESTONE = 10; /** * Define pricing schedule using milestones. */ struct Milestone { // Milestone index in array uint256 index; // UNIX timestamp when this milestone starts uint256 startTime; // Amount of tokens sold in milestone uint256 tokensSold; // Maximum amount of Tokens accepted in the current Milestone. uint256 cap; // How many tokens per wei you will get after this milestone has been passed uint256 rate; } /** * Store milestones in a fixed array, so that it can be seen in a blockchain explorer * Milestone 0 is always (0, 0) * (TODO: change this when we confirm dynamic arrays are explorable) */ Milestone[10] public milestones; // How many active milestones have been created uint256 public milestoneCount = 0; bool public milestoningFinished = false; constructor( uint256 _openingTime, uint256 _closingTime ) TimedCrowdsale(_openingTime, _closingTime) public { } /** * @dev Contruction, setting a list of milestones * @param _milestoneStartTime uint[] milestones start time * @param _milestoneCap uint[] milestones cap * @param _milestoneRate uint[] milestones price */ function setMilestonesList(uint256[] _milestoneStartTime, uint256[] _milestoneCap, uint256[] _milestoneRate) public { // Need to have tuples, length check require(!milestoningFinished); require(_milestoneStartTime.length > 0); require(_milestoneStartTime.length == _milestoneCap.length && _milestoneCap.length == _milestoneRate.length); require(_milestoneStartTime[0] == openingTime); require(_milestoneStartTime[_milestoneStartTime.length-1] < closingTime); for (uint iterator = 0; iterator < _milestoneStartTime.length; iterator++) { if (iterator > 0) { assert(_milestoneStartTime[iterator] > milestones[iterator-1].startTime); } milestones[iterator] = Milestone({ index: iterator, startTime: _milestoneStartTime[iterator], tokensSold: 0, cap: _milestoneCap[iterator], rate: _milestoneRate[iterator] }); milestoneCount++; } milestoningFinished = true; } /** * @dev Iterate through milestones. You reach end of milestones when rate = 0 * @return tuple (time, rate) */ function getMilestoneTimeAndRate(uint256 n) public view returns (uint256, uint256) { return (milestones[n].startTime, milestones[n].rate); } /** * @dev Checks whether the cap of a milestone has been reached. * @return Whether the cap was reached */ function capReached(uint256 n) public view returns (bool) { return milestones[n].tokensSold >= milestones[n].cap; } /** * @dev Checks amount of tokens sold in milestone. * @return Amount of tokens sold in milestone */ function getTokensSold(uint256 n) public view returns (uint256) { return milestones[n].tokensSold; } function getFirstMilestone() private view returns (Milestone) { return milestones[0]; } function getLastMilestone() private view returns (Milestone) { return milestones[milestoneCount-1]; } function getFirstMilestoneStartsAt() public view returns (uint256) { return getFirstMilestone().startTime; } function getLastMilestoneStartsAt() public view returns (uint256) { return getLastMilestone().startTime; } /** * @dev Get the current milestone or bail out if we are not in the milestone periods. * @return {[type]} [description] */ function getCurrentMilestoneIndex() internal view onlyWhileOpen returns (uint256) { uint256 index; // Found the current milestone by evaluating time. // If (now < next start) the current milestone is the previous // Stops loop if finds current for(uint i = 0; i < milestoneCount; i++) { index = i; // solium-disable-next-line security/no-block-members if(block.timestamp < milestones[i].startTime) { index = i - 1; break; } } // For the next code, you may ask why not assert if last milestone surpass cap... // Because if its last and it is capped we would like to finish not sell any more tokens // Check if the current milestone has reached it's cap if (milestones[index].tokensSold > milestones[index].cap) { index = index + 1; } return index; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap from the currentMilestone. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed * @param _tokenAmount Amount of token purchased */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount); require(milestones[getCurrentMilestoneIndex()].tokensSold.add(_tokenAmount) <= milestones[getCurrentMilestoneIndex()].cap); } /** * @dev Extend parent behavior to update current milestone state and index * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed * @param _tokenAmount Amount of token purchased */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { super._updatePurchasingState(_beneficiary, _weiAmount, _tokenAmount); milestones[getCurrentMilestoneIndex()].tokensSold = milestones[getCurrentMilestoneIndex()].tokensSold.add(_tokenAmount); } /** * @dev Get the current price. * @return The current price or 0 if we are outside milestone period */ function getCurrentRate() internal view returns (uint result) { return milestones[getCurrentMilestoneIndex()].rate; } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(getCurrentRate()); } } // File: contracts/price/USDPrice.sol /** * @title USDPrice * @dev Contract that calculates the price of tokens in USD cents. * Note that this contracts needs to be updated */ contract USDPrice is Ownable { using SafeMath for uint256; // PRICE of 1 ETHER in USD in cents // So, if price is: $271.90, the value in variable will be: 27190 uint256 public ETHUSD; // Time of Last Updated Price uint256 public updatedTime; // Historic price of ETH in USD in cents mapping (uint256 => uint256) public priceHistory; event PriceUpdated(uint256 price); constructor() public { } function getHistoricPrice(uint256 time) public view returns (uint256) { return priceHistory[time]; } function updatePrice(uint256 price) public onlyOwner { require(price > 0); priceHistory[updatedTime] = ETHUSD; ETHUSD = price; // solium-disable-next-line security/no-block-members updatedTime = block.timestamp; emit PriceUpdated(ETHUSD); } /** * @dev Override to extend the way in which ether is converted to USD. * @param _weiAmount Value in wei to be converted into tokens * @return The value of wei amount in USD cents */ function getPrice(uint256 _weiAmount) public view returns (uint256) { return _weiAmount.mul(ETHUSD); } } // File: contracts/PreSale.sol interface MintableERC20 { function mint(address _to, uint256 _amount) public returns (bool); } /** * @title PreSale * @dev Crowdsale accepting contributions only within a time frame, * having milestones defined, the price is defined in USD * having a mechanism to refund sales if soft cap not capReached(); * And an escrow to support the refund. */ contract PreSale is Ownable, Crowdsale, MilestoneCrowdsale { using SafeMath for uint256; /// Max amount of tokens to be contributed uint256 public cap; /// Minimum amount of wei per contribution uint256 public minimumContribution; /// minimum amount of funds to be raised in weis uint256 public goal; bool public isFinalized = false; /// refund escrow used to hold funds while crowdsale is running RefundEscrow private escrow; USDPrice private usdPrice; event Finalized(); constructor( uint256 _rate, address _wallet, ERC20 _token, uint256 _openingTime, uint256 _closingTime, uint256 _goal, uint256 _cap, uint256 _minimumContribution, USDPrice _usdPrice ) Crowdsale(_rate, _wallet, _token) MilestoneCrowdsale(_openingTime, _closingTime) public { require(_cap > 0); require(_minimumContribution > 0); require(_goal > 0); cap = _cap; minimumContribution = _minimumContribution; escrow = new RefundEscrow(wallet); goal = _goal; usdPrice = _usdPrice; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return tokensSold >= cap; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); escrow.withdraw(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return tokensSold >= goal; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(goalReached() || hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return usdPrice.getPrice(_weiAmount).div(getCurrentRate()); } /** * @dev Extend parent behavior sending heartbeat to token. * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase * @param _tokenAmount Value in token involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { super._updatePurchasingState(_beneficiary, _weiAmount, _tokenAmount); } /** * @dev Overrides delivery by minting tokens upon purchase. - MINTED Crowdsale * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { // Potentially dangerous assumption about the type of the token. require(MintableERC20(address(token)).mint(_beneficiary, _tokenAmount)); } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed * @param _tokenAmount Amount of token purchased */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount); require(_weiAmount >= minimumContribution); require(tokensSold.add(_tokenAmount) <= cap); } /** * @dev escrow finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { escrow.close(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } }
TOD1
pragma solidity ^0.4.11; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { revert(); } } } contract ZTRToken{ function transfer(address _to, uint val); } contract ZTRTokenSale { using SafeMath for uint; mapping (address => uint) public balanceOf; mapping (address => uint) public ethBalance; address public owner; address ZTRTokenContract; uint public fundingGoal; uint public fundingMax; uint public amountRaised; uint public start; uint public duration; uint public deadline; uint public unlockTime; uint public ZTR_ETH_initial_price; uint public ZTR_ETH_extra_price; uint public remaining; modifier admin { if (msg.sender == owner) _; } modifier afterUnlock { if(now>unlockTime) _;} modifier afterDeadline { if(now>deadline) _;} function ZTRTokenSale() { owner = msg.sender; ZTRTokenContract = 0x107bc486966eCdDAdb136463764a8Eb73337c4DF; fundingGoal = 5000 ether;//funds will be returned if this goal is not met fundingMax = 30000 ether;//The max amount that can be raised start = 1517702401;//beginning of the token sale duration = 3 weeks;//duration of the token sale deadline = start + duration;//end of the token sale unlockTime = deadline + 16 weeks;//unlock for selfdestruct ZTR_ETH_initial_price = 45000;//initial ztr price ZTR_ETH_extra_price = 23000;//ztr price after funding goal has been met remaining = 800000000000000000000000000;//counter for remaining tokens } function () payable public//order processing and crediting to escrow { require(now>start); require(now<deadline); require(amountRaised + msg.value < fundingMax);//funding hard cap has not been reached uint purchase = msg.value; ethBalance[msg.sender] = ethBalance[msg.sender].add(purchase);//track the amount of eth contributed for refunds if(amountRaised < fundingGoal)//funding goal has not been met yet { purchase = purchase.mul(ZTR_ETH_initial_price); amountRaised = amountRaised.add(msg.value); balanceOf[msg.sender] = balanceOf[msg.sender].add(purchase); remaining.sub(purchase); } else//funding goal has been met, selling extra tokens { purchase = purchase.mul(ZTR_ETH_extra_price); amountRaised = amountRaised.add(msg.value); balanceOf[msg.sender] = balanceOf[msg.sender].add(purchase); remaining.sub(purchase); } } function withdrawBeneficiary() public admin afterDeadline//withdrawl for the ZTrust Foundation { ZTRToken t = ZTRToken(ZTRTokenContract); t.transfer(msg.sender, remaining); require(amountRaised >= fundingGoal);//allow admin withdrawl if funding goal is reached and the sale is over owner.transfer(amountRaised); } function withdraw() afterDeadline//ETH/ZTR withdrawl for sale participants { if(amountRaised < fundingGoal)//funding goal was not met, withdraw ETH deposit { uint ethVal = ethBalance[msg.sender]; ethBalance[msg.sender] = 0; msg.sender.transfer(ethVal); } else//funding goal was met, withdraw ZTR tokens { uint tokenVal = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; ZTRToken t = ZTRToken(ZTRTokenContract); t.transfer(msg.sender, tokenVal); } } function setDeadline(uint ti) public admin//setter { deadline = ti; } function setStart(uint ti) public admin//setter { start = ti; } function suicide() public afterUnlock //contract can be destroyed 4 months after the sale ends to save state { selfdestruct(owner); } }
TOD1
pragma solidity ^0.4.24; pragma solidity ^0.4.24; pragma solidity ^0.4.20; contract CutieCoreInterface { function isCutieCore() pure public returns (bool); function transferFrom(address _from, address _to, uint256 _cutieId) external; function transfer(address _to, uint256 _cutieId) external; function ownerOf(uint256 _cutieId) external view returns (address owner); function getCutie(uint40 _id) external view returns ( uint256 genes, uint40 birthTime, uint40 cooldownEndTime, uint40 momId, uint40 dadId, uint16 cooldownIndex, uint16 generation ); function getGenes(uint40 _id) public view returns ( uint256 genes ); function getCooldownEndTime(uint40 _id) public view returns ( uint40 cooldownEndTime ); function getCooldownIndex(uint40 _id) public view returns ( uint16 cooldownIndex ); function getGeneration(uint40 _id) public view returns ( uint16 generation ); function getOptional(uint40 _id) public view returns ( uint64 optional ); function changeGenes( uint40 _cutieId, uint256 _genes) public; function changeCooldownEndTime( uint40 _cutieId, uint40 _cooldownEndTime) public; function changeCooldownIndex( uint40 _cutieId, uint16 _cooldownIndex) public; function changeOptional( uint40 _cutieId, uint64 _optional) public; function changeGeneration( uint40 _cutieId, uint16 _generation) public; } pragma solidity ^0.4.20; pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity ^0.4.24; /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract MarketInterface { function withdrawEthFromBalance() external; function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable; function bid(uint40 _cutieId) public payable; function cancelActiveAuctionWhenPaused(uint40 _cutieId) public; function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee, bool tokensAllowed ); } pragma solidity ^0.4.24; // https://etherscan.io/address/0x4118d7f757ad5893b8fa2f95e067994e1f531371#code interface ERC20 { /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on 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) external returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool success); /** * 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) external; /// @notice Count all tokens assigned to an owner function balanceOf(address _owner) external view returns (uint256); } pragma solidity ^0.4.24; // https://etherscan.io/address/0x3127be52acba38beab6b4b3a406dc04e557c037c#code contract PriceOracleInterface { // How much TOKENs you get for 1 ETH, multiplied by 10^18 uint256 public ETHPrice; } pragma solidity ^0.4.24; interface TokenRecipientInterface { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract Market is MarketInterface, Pausable, TokenRecipientInterface { // Shows the auction on an Cutie Token struct Auction { // Price (in wei or tokens) at the beginning of auction uint128 startPrice; // Price (in wei or tokens) at the end of auction uint128 endPrice; // Current owner of Token address seller; // Auction duration in seconds uint40 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint40 startedAt; // Featuring fee (in wei, optional) uint128 featuringFee; // is it allowed to bid with erc20 tokens bool tokensAllowed; } // Reference to contract that tracks ownership CutieCoreInterface public coreContract; // Cut owner takes on each auction, in basis points - 1/100 of a per cent. // Values 0-10,000 map to 0%-100% uint16 public ownerFee; // Map from token ID to their corresponding auction. mapping (uint40 => Auction) public cutieIdToAuction; mapping (address => PriceOracleInterface) public priceOracle; address operatorAddress; event AuctionCreated(uint40 indexed cutieId, uint128 startPrice, uint128 endPrice, uint40 duration, uint128 fee, bool tokensAllowed); event AuctionSuccessful(uint40 indexed cutieId, uint128 totalPriceWei, address indexed winner); event AuctionSuccessfulForToken(uint40 indexed cutieId, uint128 totalPriceWei, address indexed winner, uint128 priceInTokens, address indexed token); event AuctionCancelled(uint40 indexed cutieId); modifier onlyOperator() { require(msg.sender == operatorAddress || msg.sender == owner); _; } function setOperator(address _newOperator) public onlyOwner { require(_newOperator != address(0)); operatorAddress = _newOperator; } /// @dev disables sending fund to this contract function() external {} modifier canBeStoredIn128Bits(uint256 _value) { require(_value <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); _; } // @dev Adds to the list of open auctions and fires the // AuctionCreated event. // @param _cutieId The token ID is to be put on auction. // @param _auction To add an auction. // @param _fee Amount of money to feature auction function _addAuction(uint40 _cutieId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); cutieIdToAuction[_cutieId] = _auction; emit AuctionCreated( _cutieId, _auction.startPrice, _auction.endPrice, _auction.duration, _auction.featuringFee, _auction.tokensAllowed ); } // @dev Returns true if the token is claimed by the claimant. // @param _claimant - Address claiming to own the token. function _isOwner(address _claimant, uint256 _cutieId) internal view returns (bool) { return (coreContract.ownerOf(_cutieId) == _claimant); } // @dev Transfers the token owned by this contract to another address. // Returns true when the transfer succeeds. // @param _receiver - Address to transfer token to. // @param _cutieId - Token ID to transfer. function _transfer(address _receiver, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transfer(_receiver, _cutieId); } // @dev Escrows the token and assigns ownership to this contract. // Throws if the escrow fails. // @param _owner - Current owner address of token to escrow. // @param _cutieId - Token ID the approval of which is to be verified. function _escrow(address _owner, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transferFrom(_owner, this, _cutieId); } // @dev just cancel auction. function _cancelActiveAuction(uint40 _cutieId, address _seller) internal { _removeAuction(_cutieId); _transfer(_seller, _cutieId); emit AuctionCancelled(_cutieId); } // @dev Calculates the price and transfers winnings. // Does not transfer token ownership. function _bid(uint40 _cutieId, uint128 _bidAmount) internal returns (uint128) { // Get a reference to the auction struct Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); // Check that bid > current price uint128 price = _currentPrice(auction); require(_bidAmount >= price); // Provide a reference to the seller before the auction struct is deleted. address seller = auction.seller; _removeAuction(_cutieId); // Transfer proceeds to seller (if there are any!) if (price > 0 && seller != address(coreContract)) { uint128 fee = _computeFee(price); uint128 sellerValue = price - fee; seller.transfer(sellerValue); } emit AuctionSuccessful(_cutieId, price, msg.sender); return price; } // @dev Removes from the list of open auctions. // @param _cutieId - ID of token on auction. function _removeAuction(uint40 _cutieId) internal { delete cutieIdToAuction[_cutieId]; } // @dev Returns true if the token is on auction. // @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } // @dev calculate current price of auction. // When testing, make this function public and turn on // `Current price calculation` test suite. function _computeCurrentPrice( uint128 _startPrice, uint128 _endPrice, uint40 _duration, uint40 _secondsPassed ) internal pure returns (uint128) { if (_secondsPassed >= _duration) { return _endPrice; } else { int256 totalPriceChange = int256(_endPrice) - int256(_startPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); uint128 currentPrice = _startPrice + uint128(currentPriceChange); return currentPrice; } } // @dev return current price of token. function _currentPrice(Auction storage _auction) internal view returns (uint128) { uint40 secondsPassed = 0; uint40 timeNow = uint40(now); if (timeNow > _auction.startedAt) { secondsPassed = timeNow - _auction.startedAt; } return _computeCurrentPrice( _auction.startPrice, _auction.endPrice, _auction.duration, secondsPassed ); } // @dev Calculates owner's cut of a sale. // @param _price - Sale price of cutie. function _computeFee(uint128 _price) internal view returns (uint128) { return _price * ownerFee / 10000; } // @dev Remove all Ether from the contract with the owner's cuts. Also, remove any Ether sent directly to the contract address. // Transfers to the token contract, but can be called by // the owner or the token contract. function withdrawEthFromBalance() external { address coreAddress = address(coreContract); require( msg.sender == owner || msg.sender == coreAddress ); coreAddress.transfer(address(this).balance); } // @dev create and begin new auction. function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public whenNotPaused payable { require(_isOwner(msg.sender, _cutieId)); _escrow(msg.sender, _cutieId); bool allowTokens = _duration < 0x8000000000; // first bit of duration is boolean flag (1 to disable tokens) _duration = _duration % 0x8000000000; // clear flag from duration Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now), uint128(msg.value), allowTokens ); _addAuction(_cutieId, auction); } // @dev Set the reference to cutie ownership contract. Verify the owner's fee. // @param fee should be between 0-10,000. function setup(address _coreContractAddress, uint16 _fee) public onlyOwner { require(_fee <= 10000); ownerFee = _fee; CutieCoreInterface candidateContract = CutieCoreInterface(_coreContractAddress); require(candidateContract.isCutieCore()); coreContract = candidateContract; } // @dev Set the owner's fee. // @param fee should be between 0-10,000. function setFee(uint16 _fee) public onlyOwner { require(_fee <= 10000); ownerFee = _fee; } // @dev bid on auction. Complete it and transfer ownership of cutie if enough ether was given. function bid(uint40 _cutieId) public payable whenNotPaused canBeStoredIn128Bits(msg.value) { // _bid throws if something failed. _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } function getPriceInToken(ERC20 _tokenContract, uint128 priceWei) public view returns (uint128) { PriceOracleInterface oracle = priceOracle[address(_tokenContract)]; require(address(oracle) != address(0)); uint256 ethPerToken = oracle.ETHPrice(); return uint128(uint256(priceWei) * ethPerToken / 1 ether); } function getCutieId(bytes _extraData) pure internal returns (uint40) { return uint40(_extraData[0]) + uint40(_extraData[1]) * 0x100 + uint40(_extraData[2]) * 0x10000 + uint40(_extraData[3]) * 0x100000 + uint40(_extraData[4]) * 0x10000000; } // https://github.com/BitGuildPlatform/Documentation/blob/master/README.md#2-required-game-smart-contract-changes // Function that is called when trying to use PLAT for payments from approveAndCall function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData) external canBeStoredIn128Bits(_value) whenNotPaused { ERC20 tokenContract = ERC20(_tokenContract); require(_extraData.length == 5); // 40 bits uint40 cutieId = getCutieId(_extraData); // Get a reference to the auction struct Auction storage auction = cutieIdToAuction[cutieId]; require(auction.tokensAllowed); // buy for token is allowed require(_isOnAuction(auction)); uint128 priceWei = _currentPrice(auction); uint128 priceInTokens = getPriceInToken(tokenContract, priceWei); // Check that bid > current price //require(_value >= priceInTokens); // Provide a reference to the seller before the auction struct is deleted. address seller = auction.seller; _removeAuction(cutieId); // Transfer proceeds to seller (if there are any!) if (priceInTokens > 0 && seller != address(coreContract)) { uint128 fee = _computeFee(priceInTokens); uint128 sellerValue = priceInTokens - fee; require(tokenContract.transferFrom(_sender, address(this), priceInTokens)); tokenContract.transfer(seller, sellerValue); } emit AuctionSuccessfulForToken(cutieId, priceWei, _sender, priceInTokens, _tokenContract); _transfer(_sender, cutieId); } // @dev Returns auction info for a token on auction. // @param _cutieId - ID of token on auction. function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee, bool tokensAllowed ) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt, auction.featuringFee, auction.tokensAllowed ); } // @dev Returns auction info for a token on auction. // @param _cutieId - ID of token on auction. function isOnAuction(uint40 _cutieId) public view returns (bool) { return cutieIdToAuction[_cutieId].startedAt > 0; } /* /// @dev Import cuties from previous version of Core contract. /// @param _oldAddress Old core contract address /// @param _fromIndex (inclusive) /// @param _toIndex (inclusive) function migrate(address _oldAddress, uint40 _fromIndex, uint40 _toIndex) public onlyOwner whenPaused { Market old = Market(_oldAddress); for (uint40 i = _fromIndex; i <= _toIndex; i++) { if (coreContract.ownerOf(i) == _oldAddress) { address seller; uint128 startPrice; uint128 endPrice; uint40 duration; uint40 startedAt; uint128 featuringFee; (seller, startPrice, endPrice, duration, startedAt, featuringFee) = old.getAuctionInfo(i); Auction memory auction = Auction({ seller: seller, startPrice: startPrice, endPrice: endPrice, duration: duration, startedAt: startedAt, featuringFee: featuringFee }); _addAuction(i, auction); } } }*/ // @dev Returns the current price of an auction. function getCurrentPrice(uint40 _cutieId) public view returns (uint128) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return _currentPrice(auction); } // @dev Cancels unfinished auction and returns token to owner. // Can be called when contract is paused. function cancelActiveAuction(uint40 _cutieId) public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelActiveAuction(_cutieId, seller); } // @dev Cancels auction when contract is on pause. Option is available only to owners in urgent situations. Tokens returned to seller. // Used on Core contract upgrade. function cancelActiveAuctionWhenPaused(uint40 _cutieId) whenPaused onlyOwner public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); _cancelActiveAuction(_cutieId, auction.seller); } // @dev Cancels unfinished auction and returns token to owner. // Can be called when contract is paused. function cancelCreatorAuction(uint40 _cutieId) public onlyOperator { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); address seller = auction.seller; require(seller == address(coreContract)); _cancelActiveAuction(_cutieId, msg.sender); } // @dev Transfers to _withdrawToAddress all tokens controlled by // contract _tokenContract. function withdrawTokenFromBalance(ERC20 _tokenContract, address _withdrawToAddress) external { address coreAddress = address(coreContract); require( msg.sender == owner || msg.sender == operatorAddress || msg.sender == coreAddress ); uint256 balance = _tokenContract.balanceOf(address(this)); _tokenContract.transfer(_withdrawToAddress, balance); } /// @dev Allow buy cuties for token function addToken(ERC20 _tokenContract, PriceOracleInterface _priceOracle) external onlyOwner { priceOracle[address(_tokenContract)] = _priceOracle; } /// @dev Disallow buy cuties for token function removeToken(ERC20 _tokenContract) external onlyOwner { delete priceOracle[address(_tokenContract)]; } } /// @title Auction market for cuties sale /// @author https://BlockChainArchitect.io contract SaleMarket is Market { // @dev Sanity check reveals that the // auction in our setSaleAuctionAddress() call is right. bool public isSaleMarket = true; // @dev create and start a new auction // @param _cutieId - ID of cutie to auction, sender must be owner. // @param _startPrice - Price of item (in wei) at the beginning of auction. // @param _endPrice - Price of item (in wei) at the end of auction. // @param _duration - Length of auction (in seconds). // @param _seller - Seller function createAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller ) public payable { require(msg.sender == address(coreContract)); _escrow(_seller, _cutieId); bool allowTokens = _duration < 0x8000000000; // first bit of duration is boolean flag (1 to disable tokens) _duration = _duration % 0x8000000000; // clear flag from duration Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now), uint128(msg.value), allowTokens ); _addAuction(_cutieId, auction); } // @dev LastSalePrice is updated if seller is the token contract. // Otherwise, default bid method is used. function bid(uint40 _cutieId) public payable canBeStoredIn128Bits(msg.value) { // _bid verifies token ID size _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } }
TOD1
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(_beneficiary, _weiAmount); * require(weiRaised.add(_weiAmount) <= cap); * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { // Potentially dangerous assumption about the type of the token. require(MintableToken(address(token)).mint(_beneficiary, _tokenAmount)); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Ownable, TimedCrowdsale { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title Escrow * @dev Base escrow contract, holds funds destinated to a payee until they * withdraw them. The contract that uses the escrow as its payment method * should be its owner, and provide public methods redirecting to the escrow's * deposit and withdraw. */ contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param _payee The destination address of the funds. */ function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool) { return state == State.Refunding; } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund escrow used to hold funds while crowdsale is running RefundEscrow private escrow; /** * @dev Constructor, creates RefundEscrow. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); escrow = new RefundEscrow(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); escrow.withdraw(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev escrow finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { escrow.close(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } } /** * @title KHDonCrowdsale * @dev Very simple crowdsale contract for the mintable KHDon token with the following extensions: * RefundableCrowdsale - set a min goal to be reached and returns funds if it's not met * MintedCrowdsale - tokens are minted in each purchase. */ contract KHDonCrowdsale is Crowdsale, TimedCrowdsale, RefundableCrowdsale, MintedCrowdsale { constructor( uint256 _rate, address _wallet, ERC20 _token, uint256 _openingTime, uint256 _closingTime, uint256 _goal ) Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) RefundableCrowdsale(_goal) public { } }
TOD1
pragma solidity ^0.4.20; contract GUESS_THE_WORD { string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.21; // File: contracts/zeppelin-solidity/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/zeppelin-solidity/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/zeppelin-solidity/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/zeppelin-solidity/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } } // File: contracts/zeppelin-solidity/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/zeppelin-solidity/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/zeppelin-solidity/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/zeppelin-solidity/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: contracts/zeppelin-solidity/ERC20/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/zeppelin-solidity/ERC827/ERC827.sol /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } // File: contracts/zeppelin-solidity/ERC827/ERC827Token.sol /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 @param _spender The address that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } // File: contracts/QuintessenceToken.sol contract AbstractQuintessenceToken is CappedToken, ERC827Token, BurnableToken { string public name = "Quintessence Token"; string public symbol = "QST"; function AbstractQuintessenceToken(uint256 initial_supply, uint256 _cap) CappedToken(_cap) public { mint(msg.sender, initial_supply); } } contract QuintessenceToken is AbstractQuintessenceToken { uint256 public constant decimals = 18; uint256 public constant TOKEN_CAP = 56000000 * (10 ** decimals); // Allocate 4% of TOKEN_CAP to the team. uint256 public constant TEAM_SUPPLY = (TOKEN_CAP * 4) / 100; function QuintessenceToken() AbstractQuintessenceToken(TEAM_SUPPLY, TOKEN_CAP) public { } } // File: contracts/zeppelin-solidity/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: contracts/zeppelin-solidity/crowdsale/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } // File: contracts/zeppelin-solidity/crowdsale/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: contracts/zeppelin-solidity/crowdsale/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= now); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: contracts/zeppelin-solidity/crowdsale/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: contracts/zeppelin-solidity/crowdsale/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } // File: contracts/zeppelin-solidity/crowdsale/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: contracts/CryptonsPreICO.sol contract DiscountedPreICO is TimedCrowdsale { using SafeMath for uint256; function DiscountedPreICO(uint256 _opening_time, uint256 _closing_time) TimedCrowdsale(_opening_time, _closing_time) public { } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate).mul(100).div(100 - getCurrentDiscount()); } /** * returns discount for the current time. */ function getCurrentDiscount() public view returns(uint256) { return 0; } } contract AbstractCryptonsPreICO is RefundableCrowdsale, DiscountedPreICO, MintedCrowdsale, CappedCrowdsale { function AbstractCryptonsPreICO(uint256 _opening_time, uint256 _closing_time, uint256 _rate, address _wallet, AbstractQuintessenceToken _token, uint256 _soft_cap, uint256 _hard_cap) RefundableCrowdsale(_soft_cap) DiscountedPreICO(_opening_time, _closing_time) CappedCrowdsale(_hard_cap) Crowdsale(_rate, _wallet, _token) public { require(_soft_cap < _hard_cap); } function finalization() internal { super.finalization(); QuintessenceToken(token).transferOwnership(msg.sender); } } contract AbstractCryptonsPreICOWithDiscount is AbstractCryptonsPreICO { function AbstractCryptonsPreICOWithDiscount( uint256 _opening_time, uint256 _closing_time, uint256 _rate, address _wallet, AbstractQuintessenceToken _token, uint256 _soft_cap, uint256 _hard_cap) AbstractCryptonsPreICO(_opening_time, _closing_time, _rate, _wallet, _token, _soft_cap, _hard_cap) public { } function getCurrentDiscount() public view returns(uint256) { if (now < openingTime + 1 weeks) return 50; return 40; } } contract CryptonsPreICO is AbstractCryptonsPreICOWithDiscount { // PreICO starts in the noon, and ends 2 weeks later in the evening. uint256 public constant OPENING_TIME = 1523880000; // 2018-04-16 12:00:00+00:00 (UTC) uint256 public constant CLOSING_TIME = 1525125599; // 2018-04-30 21:59:59+00:00 (UTC) uint256 public constant ETH_TO_QST_TOKEN_RATE = 1000; uint256 public constant SOFT_CAP = 656 ether; uint256 public constant HARD_CAP = 2624 ether; function CryptonsPreICO(address _wallet, QuintessenceToken _token) AbstractCryptonsPreICOWithDiscount(OPENING_TIME, CLOSING_TIME, ETH_TO_QST_TOKEN_RATE, _wallet, _token, SOFT_CAP, HARD_CAP) public { // Check if we didn't set up the opening and closing time to far in // the future by accident. require(now + 1 weeks > openingTime); require(openingTime + 2 weeks + 10 hours > closingTime); } }
TOD1
pragma solidity ^0.4.25; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract IERC721 { 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; } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20BasicInterface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); uint8 public decimals; } contract Bussiness is Ownable { address public ceoAddress = address(0x6c3e879bdd20e9686cfd9bbd1bfd4b2dd6d47079); IERC721 public erc721Address = IERC721(0x5d00d312e171be5342067c09bae883f9bcb2003b); ERC20BasicInterface public usdtToken = ERC20BasicInterface(0xdac17f958d2ee523a2206206994597c13d831ec7); uint256 public ETHFee = 2; uint256 public HBWALLETFee = 1; constructor() public {} struct Price { address tokenOwner; uint256 price; uint256 fee; } mapping(uint256 => Price) public prices; mapping(uint256 => Price) public usdtPrices; /** * @dev Throws if called by any account other than the ceo address. */ modifier onlyCeoAddress() { require(msg.sender == ceoAddress); _; } function ownerOf(uint256 _tokenId) public view returns (address){ return erc721Address.ownerOf(_tokenId); } function balanceOf() public view returns (uint256){ return address(this).balance; } function getApproved(uint256 _tokenId) public view returns (address){ return erc721Address.getApproved(_tokenId); } function setPrice(uint256 _tokenId, uint256 _ethPrice, uint256 _usdtPrice) public { require(erc721Address.ownerOf(_tokenId) == msg.sender); prices[_tokenId] = Price(msg.sender, _ethPrice, 0); usdtPrices[_tokenId] = Price(msg.sender, _usdtPrice, 0); } function setPriceFeeEth(uint256 _tokenId, uint256 _ethPrice) public payable { require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice); uint256 ethfee; if(prices[_tokenId].price < _ethPrice) { ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / 100; require(msg.value == ethfee); ethfee += prices[_tokenId].fee; } else ethfee = _ethPrice * ETHFee / 100; prices[_tokenId] = Price(msg.sender, _ethPrice, ethfee); } function removePrice(uint256 tokenId) public returns (uint256){ require(erc721Address.ownerOf(tokenId) == msg.sender); if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee); resetPrice(tokenId); return prices[tokenId].price; } function getPrice(uint256 tokenId) public view returns (address, address, uint256, uint256){ address currentOwner = erc721Address.ownerOf(tokenId); if(prices[tokenId].tokenOwner != currentOwner){ resetPrice(tokenId); } return (currentOwner, prices[tokenId].tokenOwner, prices[tokenId].price, usdtPrices[tokenId].price); } function setFee(uint256 _ethFee, uint256 _hbWalletFee) public view onlyOwner returns (uint256 _ETHFee, uint256 _HBWALLETFee){ require(_ethFee > 0 && _hbWalletFee > 0); _ETHFee = _ethFee; _HBWALLETFee = _hbWalletFee; return (_ETHFee, _HBWALLETFee); } /** * @dev Withdraw the amount of eth that is remaining in this contract. * @param _address The address of EOA that can receive token from this contract. */ function withdraw(address _address, uint256 amount) public onlyCeoAddress { require(_address != address(0) && amount > 0 && address(this).balance > amount); _address.transfer(amount); } function buy(uint256 tokenId) public payable { require(getApproved(tokenId) == address(this)); require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value); erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId); prices[tokenId].tokenOwner.transfer(msg.value); resetPrice(tokenId); } function buyWithoutCheckApproved(uint256 tokenId) public payable { require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value); erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId); prices[tokenId].tokenOwner.transfer(msg.value); resetPrice(tokenId); } function buyByUsdt(uint256 tokenId) public { require(usdtPrices[tokenId].price > 0 && erc721Address.getApproved(tokenId) == address(this)); require(usdtToken.transferFrom(msg.sender, usdtPrices[tokenId].tokenOwner, usdtPrices[tokenId].price)); erc721Address.transferFrom(usdtPrices[tokenId].tokenOwner, msg.sender, tokenId); resetPrice(tokenId); } function resetPrice(uint256 tokenId) private { prices[tokenId] = Price(address(0), 0, 0); usdtPrices[tokenId] = Price(address(0), 0, 0); } }
TOD1
pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/ExchangerI.sol contract ExchangerI { ERC20Basic public wpr; /// @notice This method should be called by the WCT holders to collect their /// corresponding WPRs function collect(address caller) public; } // File: contracts/MiniMeToken.sol /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data); } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'MMT_0.1'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success) { // The controller of this contract can move tokens around at will, // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/token/PausableToken.sol /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/WPR.sol /** * @title WePower Contribution Token */ contract WPR is MintableToken, PausableToken { string constant public name = "WePower Token"; string constant public symbol = "WPR"; uint constant public decimals = 18; function WPR() { } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyOwner { if (_token == 0x0) { owner.transfer(this.balance); return; } ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); function disown() public onlyOwner { OwnershipTransferred(owner, address(0)); owner = address(0); } } // File: contracts/Contribution.sol contract Contribution is Ownable { using SafeMath for uint256; WPR public wpr; address public contributionWallet; address public teamHolder; address public communityHolder; address public futureHolder; address public exchanger; // Wings Integration uint256 public totalCollected; uint256 public totalWeiCap; // Total Wei to be collected uint256 public totalWeiCollected; // How much Wei has been collected uint256 public presaleTokensIssued; uint256 public minimumPerTransaction = 0.01 ether; uint256 public numWhitelistedInvestors; mapping (address => bool) public canPurchase; mapping (address => uint256) public individualWeiCollected; uint256 public startTime; uint256 public endTime; uint256 public initializedTime; uint256 public finalizedTime; uint256 public initializedBlock; uint256 public finalizedBlock; bool public paused; modifier initialized() { require(initializedBlock != 0); _; } modifier contributionOpen() { require(getBlockTimestamp() >= startTime && getBlockTimestamp() <= endTime && finalizedTime == 0); _; } modifier notPaused() { require(!paused); _; } function Contribution(address _wpr) { require(_wpr != 0x0); wpr = WPR(_wpr); } function initialize( address _wct1, address _wct2, address _exchanger, address _contributionWallet, address _futureHolder, address _teamHolder, address _communityHolder, uint256 _totalWeiCap, uint256 _startTime, uint256 _endTime ) public onlyOwner { // Initialize only once require(initializedBlock == 0); require(initializedTime == 0); assert(wpr.totalSupply() == 0); assert(wpr.owner() == address(this)); assert(wpr.decimals() == 18); // Same amount of decimals as ETH wpr.pause(); require(_contributionWallet != 0x0); contributionWallet = _contributionWallet; require(_futureHolder != 0x0); futureHolder = _futureHolder; require(_teamHolder != 0x0); teamHolder = _teamHolder; require(_communityHolder != 0x0); communityHolder = _communityHolder; require(_startTime >= getBlockTimestamp()); require(_startTime < _endTime); startTime = _startTime; endTime = _endTime; require(_totalWeiCap > 0); totalWeiCap = _totalWeiCap; initializedBlock = getBlockNumber(); initializedTime = getBlockTimestamp(); require(_wct1 != 0x0); require(_wct2 != 0x0); require(_exchanger != 0x0); presaleTokensIssued = MiniMeToken(_wct1).totalSupplyAt(initializedBlock); presaleTokensIssued = presaleTokensIssued.add( MiniMeToken(_wct2).totalSupplyAt(initializedBlock) ); // Exchange rate from wct to wpr 10000 require(wpr.mint(_exchanger, presaleTokensIssued.mul(10000))); exchanger = _exchanger; Initialized(initializedBlock); } /// @notice interface for founders to blacklist investors /// @param _investors array of investors function blacklistAddresses(address[] _investors) public onlyOwner { for (uint256 i = 0; i < _investors.length; i++) { blacklist(_investors[i]); } } /// @notice Notifies if an investor is whitelisted for contribution /// @param _investor investor address /// @return status function isWhitelisted(address _investor) public onlyOwner constant returns(bool) { return canPurchase[_investor]; } /// @notice interface for founders to whitelist investors /// @param _investors array of investors function whitelistAddresses(address[] _investors) public onlyOwner { for (uint256 i = 0; i < _investors.length; i++) { whitelist(_investors[i]); } } function whitelist(address investor) public onlyOwner { if (canPurchase[investor]) return; numWhitelistedInvestors++; canPurchase[investor] = true; } function blacklist(address investor) public onlyOwner { if (!canPurchase[investor]) return; numWhitelistedInvestors--; canPurchase[investor] = false; } // ETH-WPR exchange rate function exchangeRate() constant public initialized returns (uint256) { return 8000; } function tokensToGenerate(uint256 toFund) internal returns (uint256 generatedTokens) { generatedTokens = toFund.mul(exchangeRate()); } /// @notice If anybody sends Ether directly to this contract, consider he is /// getting WPRs. function () public payable notPaused { proxyPayment(msg.sender); } ////////// // TokenController functions ////////// /// @notice This method will generally be called by the WPR token contract to /// acquire WPRs. Or directly from third parties that want to acquire WPRs in /// behalf of a token holder. /// @param _th WPR holder where the WPRs will be minted. function proxyPayment(address _th) public payable notPaused initialized contributionOpen returns (bool) { require(_th != 0x0); if (msg.value == 0) { wpr.unpause(); ExchangerI(exchanger).collect(_th); wpr.pause(); } else { doBuy(_th); } return true; } function doBuy(address _th) internal { // whitelisting only during the first day // if (getBlockTimestamp() <= startTime + 1 days) { require(canPurchase[_th]); // } require(msg.value >= minimumPerTransaction); uint256 toFund = msg.value; uint256 toCollect = weiToCollectByInvestor(_th); require(toCollect > 0); // Check total supply cap reached, sell the all remaining tokens if (toFund > toCollect) { toFund = toCollect; } uint256 tokensGenerated = tokensToGenerate(toFund); require(tokensGenerated > 0); require(wpr.mint(_th, tokensGenerated)); contributionWallet.transfer(toFund); // Wings Integration totalCollected = totalCollected.add(toFund); individualWeiCollected[_th] = individualWeiCollected[_th].add(toFund); totalWeiCollected = totalWeiCollected.add(toFund); NewSale(_th, toFund, tokensGenerated); uint256 toReturn = msg.value.sub(toFund); if (toReturn > 0) { _th.transfer(toReturn); } } /// @notice This method will can be called by the controller before the contribution period /// end or by anybody after the `endTime`. This method finalizes the contribution period /// by creating the remaining tokens and transferring the controller to the configured /// controller. function finalize() public initialized { require(finalizedBlock == 0); require(finalizedTime == 0); require(getBlockTimestamp() >= startTime); require(msg.sender == owner || getBlockTimestamp() > endTime || weiToCollect() == 0); uint CROWDSALE_PCT = 62; uint TEAMHOLDER_PCT = 20; uint COMMUNITYHOLDER_PCT = 15; uint FUTUREHOLDER_PCT = 3; assert(CROWDSALE_PCT + TEAMHOLDER_PCT + COMMUNITYHOLDER_PCT + FUTUREHOLDER_PCT == 100); // WPR generated so far is 62% of total uint256 tokenCap = wpr.totalSupply().mul(100).div(CROWDSALE_PCT); // team Wallet will have 20% of the total Tokens and will be in a 36 months // vesting contract with 3 months cliff. wpr.mint(teamHolder, tokenCap.mul(TEAMHOLDER_PCT).div(100)); // community Wallet will have access to 15% of the total Tokens. wpr.mint(communityHolder, tokenCap.mul(COMMUNITYHOLDER_PCT).div(100)); // future Wallet will have 3% of the total Tokens and will be able to retrieve // after a 4 years. wpr.mint(futureHolder, tokenCap.mul(FUTUREHOLDER_PCT).div(100)); require(wpr.finishMinting()); wpr.transferOwnership(owner); finalizedBlock = getBlockNumber(); finalizedTime = getBlockTimestamp(); Finalized(finalizedBlock); } ////////// // Constant functions ////////// /// @return Total eth that still available for collection in weis. function weiToCollect() public constant returns(uint256) { return totalWeiCap > totalWeiCollected ? totalWeiCap.sub(totalWeiCollected) : 0; } /// @return Total eth that still available for collection in weis. function weiToCollectByInvestor(address investor) public constant returns(uint256) { uint256 cap; uint256 collected; // adding 1 day as a placeholder for X hours. // This should change into a variable or coded into the contract. if (getBlockTimestamp() <= startTime + 5 hours) { cap = totalWeiCap.div(numWhitelistedInvestors); collected = individualWeiCollected[investor]; } else { cap = totalWeiCap; collected = totalWeiCollected; } return cap > collected ? cap.sub(collected) : 0; } ////////// // Testing specific methods ////////// /// @notice This function is overridden by the test Mocks. function getBlockNumber() internal constant returns (uint256) { return block.number; } function getBlockTimestamp() internal constant returns (uint256) { return block.timestamp; } ////////// // Safety Methods ////////// // Wings Integration // This function can be used by the contract owner to add ether collected // outside of this contract, such as from a presale function setTotalCollected(uint _totalCollected) public onlyOwner { totalCollected = _totalCollected; } /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyOwner { if (wpr.owner() == address(this)) { wpr.claimTokens(_token); } if (_token == 0x0) { owner.transfer(this.balance); return; } ERC20 token = ERC20(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); } /// @notice Pauses the contribution if there is any issue function pauseContribution(bool _paused) onlyOwner { paused = _paused; } event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event NewSale(address indexed _th, uint256 _amount, uint256 _tokens); event Initialized(uint _now); event Finalized(uint _now); } // File: contracts/Exchanger.sol /* Copyright 2017, Klaus Hott (BlockChainLabs.nz) Copyright 2017, Jordi Baylina (Giveth) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title Exchanger Contract /// @author Klaus Hott /// @dev This contract will be used to distribute WPR between WCT holders. /// WCT token is not transferable, and we just keep an accounting between all tokens /// deposited and the tokens collected. contract Exchanger is ExchangerI, Ownable { using SafeMath for uint256; mapping (address => uint256) public collected; uint256 public totalCollected; MiniMeToken public wct1; MiniMeToken public wct2; Contribution public contribution; function Exchanger(address _wct1, address _wct2, address _wpr, address _contribution) { wct1 = MiniMeToken(_wct1); wct2 = MiniMeToken(_wct2); wpr = ERC20Basic(_wpr); contribution = Contribution(_contribution); } function () public { if (contribution.finalizedBlock() == 0) { contribution.proxyPayment(msg.sender); } else { collect(msg.sender); } } /// @notice This method should be called by the WCT holders to collect their /// corresponding WPRs function collect(address caller) public { // WCT sholder could collect WPR right after contribution started require(getBlockTimestamp() > contribution.startTime()); uint256 pre_sale_fixed_at = contribution.initializedBlock(); // Get current WPR ballance at contributions initialization- uint256 balance = wct1.balanceOfAt(caller, pre_sale_fixed_at); balance = balance.add(wct2.balanceOfAt(caller, pre_sale_fixed_at)); uint256 totalSupplied = wct1.totalSupplyAt(pre_sale_fixed_at); totalSupplied = totalSupplied.add(wct2.totalSupplyAt(pre_sale_fixed_at)); // total of wpr to be distributed. uint256 total = totalCollected.add(wpr.balanceOf(address(this))); // First calculate how much correspond to him assert(totalSupplied > 0); uint256 amount = total.mul(balance).div(totalSupplied); // And then subtract the amount already collected amount = amount.sub(collected[caller]); // Notify the user that there are no tokens to exchange require(amount > 0); totalCollected = totalCollected.add(amount); collected[caller] = collected[caller].add(amount); require(wpr.transfer(caller, amount)); TokensCollected(caller, amount); } ////////// // Testing specific methods ////////// /// @notice This function is overridden by the test Mocks. function getBlockNumber() internal constant returns (uint256) { return block.number; } /// @notice This function is overridden by the test Mocks. function getBlockTimestamp() internal constant returns (uint256) { return block.timestamp; } ////////// // Safety Method ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyOwner { assert(_token != address(wpr)); if (_token == 0x0) { owner.transfer(this.balance); return; } ERC20 token = ERC20(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event TokensCollected(address indexed _holder, uint256 _amount); }
TOD1
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/Utils/Ownable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "msg.sender not owner"); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0), "_newOwner == 0"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/Utils/Destructible.sol pragma solidity ^0.4.24; /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() public onlyOwner { selfdestruct(owner); } function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } } // File: contracts/Interfaces/IWallet.sol pragma solidity ^0.4.24; /** * @title Wallet interface. * @dev The interface of the SC that own the assets. */ interface IWallet { function transferAssetTo( address _assetAddress, address _to, uint _amount ) external payable returns (bool); function withdrawAsset( address _assetAddress, uint _amount ) external returns (bool); function setTokenSwapAllowance ( address _tokenSwapAddress, bool _allowance ) external returns(bool); } // File: contracts/Utils/Pausable.sol pragma solidity ^0.4.24; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "The contract is paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "The contract is not paused"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: contracts/Interfaces/IBadERC20.sol pragma solidity ^0.4.24; /** * @title Bad formed ERC20 token interface. * @dev The interface of the a bad formed ERC20 token. */ interface IBadERC20 { function transfer(address to, uint256 value) external; function approve(address spender, uint256 value) external; function transferFrom( address from, address to, uint256 value ) external; function totalSupply() external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/Utils/SafeTransfer.sol pragma solidity ^0.4.24; /** * @title SafeTransfer * @dev Transfer Bad ERC20 tokens */ library SafeTransfer { /** * @dev Wrapping the ERC20 transferFrom function to avoid missing returns. * @param _tokenAddress The address of bad formed ERC20 token. * @param _from Transfer sender. * @param _to Transfer receiver. * @param _value Amount to be transfered. * @return Success of the safeTransferFrom. */ function _safeTransferFrom( address _tokenAddress, address _from, address _to, uint256 _value ) internal returns (bool result) { IBadERC20(_tokenAddress).transferFrom(_from, _to, _value); assembly { switch returndatasize() case 0 { // This is our BadToken result := not(0) // result is true } case 32 { // This is our GoodToken returndatacopy(0, 0, 32) result := mload(0) // result == returndata of external call } default { // This is not an ERC20 token revert(0, 0) } } } /** * @dev Wrapping the ERC20 transfer function to avoid missing returns. * @param _tokenAddress The address of bad formed ERC20 token. * @param _to Transfer receiver. * @param _amount Amount to be transfered. * @return Success of the safeTransfer. */ function _safeTransfer( address _tokenAddress, address _to, uint _amount ) internal returns (bool result) { IBadERC20(_tokenAddress).transfer(_to, _amount); assembly { switch returndatasize() case 0 { // This is our BadToken result := not(0) // result is true } case 32 { // This is our GoodToken returndatacopy(0, 0, 32) result := mload(0) // result == returndata of external call } default { // This is not an ERC20 token revert(0, 0) } } } } // File: contracts/TokenSwap.sol pragma solidity ^0.4.24; /** * @title TokenSwap. * @author Eidoo SAGL. * @dev A swap asset contract. The offerAmount and wantAmount are collected and sent into the contract itself. */ contract TokenSwap is Pausable, Destructible { using SafeMath for uint; address public baseTokenAddress; address public quoteTokenAddress; address public wallet; uint public buyRate; uint public buyRateDecimals; uint public sellRate; uint public sellRateDecimals; event LogWithdrawToken( address indexed _from, address indexed _token, uint amount ); event LogSetWallet(address indexed _wallet); event LogSetBaseTokenAddress(address indexed _token); event LogSetQuoteTokenAddress(address indexed _token); event LogSetRateAndRateDecimals( uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ); event LogSetNumberOfZeroesFromLastDigit( uint _numberOfZeroesFromLastDigit ); event LogTokenSwap( address indexed _userAddress, address indexed _userSentTokenAddress, uint _userSentTokenAmount, address indexed _userReceivedTokenAddress, uint _userReceivedTokenAmount ); /** * @dev Contract constructor. * @param _baseTokenAddress The base of the swap pair. * @param _quoteTokenAddress The quote of the swap pair. * @param _buyRate Purchase rate, how many baseToken for the given quoteToken. * @param _buyRateDecimals Define the decimals precision for the given asset. * @param _sellRate Purchase rate, how many quoteToken for the given baseToken. * @param _sellRateDecimals Define the decimals precision for the given asset. */ constructor( address _baseTokenAddress, address _quoteTokenAddress, address _wallet, uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ) public { require(_wallet != address(0), "_wallet == address(0)"); baseTokenAddress = _baseTokenAddress; quoteTokenAddress = _quoteTokenAddress; wallet = _wallet; buyRate = _buyRate; buyRateDecimals = _buyRateDecimals; sellRate = _sellRate; sellRateDecimals = _sellRateDecimals; } function() external { revert("fallback function not allowed"); } /** * @dev Set base token address. * @param _baseTokenAddress The pair base token address. * @return bool. */ function setBaseTokenAddress(address _baseTokenAddress) public onlyOwner returns (bool) { baseTokenAddress = _baseTokenAddress; emit LogSetBaseTokenAddress(_baseTokenAddress); return true; } /** * @dev Set quote token address. * @param _quoteTokenAddress The quote token address. * @return bool. */ function setQuoteTokenAddress(address _quoteTokenAddress) public onlyOwner returns (bool) { quoteTokenAddress = _quoteTokenAddress; emit LogSetQuoteTokenAddress(_quoteTokenAddress); return true; } /** * @dev Set wallet sc address. * @param _wallet The wallet sc address. * @return bool. */ function setWallet(address _wallet) public onlyOwner returns (bool) { require(_wallet != address(0), "_wallet == address(0)"); wallet = _wallet; emit LogSetWallet(_wallet); return true; } /** * @dev Set rate. * @param _buyRate Multiplier, how many base token for the quote token. * @param _buyRateDecimals Number of significan digits of the rate. * @param _sellRate Multiplier, how many quote token for the base token. * @param _sellRateDecimals Number of significan digits of the rate. * @return bool. */ function setRateAndRateDecimals( uint _buyRate, uint _buyRateDecimals, uint _sellRate, uint _sellRateDecimals ) public onlyOwner returns (bool) { require(_buyRate != buyRate, "_buyRate == buyRate"); require(_buyRate != 0, "_buyRate == 0"); require(_sellRate != sellRate, "_sellRate == sellRate"); require(_sellRate != 0, "_sellRate == 0"); buyRate = _buyRate; sellRate = _sellRate; buyRateDecimals = _buyRateDecimals; sellRateDecimals = _sellRateDecimals; emit LogSetRateAndRateDecimals( _buyRate, _buyRateDecimals, _sellRate, _sellRateDecimals ); return true; } /** * @dev Withdraw asset. * @param _tokenAddress Asset to be withdrawed. * @return bool. */ function withdrawToken(address _tokenAddress) public onlyOwner returns(bool) { uint tokenBalance; if (isETH(_tokenAddress)) { tokenBalance = address(this).balance; msg.sender.transfer(tokenBalance); } else { tokenBalance = ERC20(_tokenAddress).balanceOf(address(this)); require( SafeTransfer._safeTransfer(_tokenAddress, msg.sender, tokenBalance), "withdraw transfer failed" ); } emit LogWithdrawToken(msg.sender, _tokenAddress, tokenBalance); return true; } /** * @dev Understand if the user swap request is a BUY or a SELL. * @param _offerTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isBuy(address _offerTokenAddress) public view returns (bool) { return _offerTokenAddress == quoteTokenAddress; } /** * @dev Understand if the token is ETH or not. * @param _tokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isETH(address _tokenAddress) public pure returns (bool) { return _tokenAddress == address(0); } /** * @dev Understand if the user swap request is for the available pair. * @param _offerTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @return bool. */ function isOfferInPair(address _offerTokenAddress) public view returns (bool) { return _offerTokenAddress == quoteTokenAddress || _offerTokenAddress == baseTokenAddress; } /** * @dev Function to calculate the number of tokens the user is going to receive. * @param _offerTokenAmount The amount of tokne number of WEI to convert in ERC20. * @return uint. */ function getAmount( uint _offerTokenAmount, bool _isBuy ) public view returns(uint) { uint amount; if (_isBuy) { amount = _offerTokenAmount.mul(buyRate).div(10 ** buyRateDecimals); } else { amount = _offerTokenAmount.mul(sellRate).div(10 ** sellRateDecimals); } return amount; } /** * @dev Release purchased asset to the buyer based on pair rate. * @param _userOfferTokenAddress The token address the purchaser is offering (It may be the quote or the base). * @param _userOfferTokenAmount The amount of token the user want to swap. * @return bool. */ function swapToken ( address _userOfferTokenAddress, uint _userOfferTokenAmount ) public whenNotPaused payable returns (bool) { require(_userOfferTokenAmount != 0, "_userOfferTokenAmount == 0"); // check if offered token address is the base or the quote token address require( isOfferInPair(_userOfferTokenAddress), "_userOfferTokenAddress not in pair" ); // check if the msg.value is consistent when offered token address is eth if (isETH(_userOfferTokenAddress)) { require(_userOfferTokenAmount == msg.value, "msg.value != _userOfferTokenAmount"); } else { require(msg.value == 0, "msg.value != 0"); } bool isUserBuy = isBuy(_userOfferTokenAddress); uint toWalletAmount = _userOfferTokenAmount; uint toUserAmount = getAmount( _userOfferTokenAmount, isUserBuy ); require(toUserAmount > 0, "toUserAmount must be greater than 0"); if (isUserBuy) { // send the quote to wallet require( _transferAmounts( msg.sender, wallet, quoteTokenAddress, toWalletAmount ), "the transfer from of the quote the user to the TokenSwap SC failed" ); // send the base to user require( _transferAmounts( wallet, msg.sender, baseTokenAddress, toUserAmount ), "the transfer of the base from the TokenSwap SC to the user failed" ); emit LogTokenSwap( msg.sender, quoteTokenAddress, toWalletAmount, baseTokenAddress, toUserAmount ); } else { // send the base to wallet require( _transferAmounts( msg.sender, wallet, baseTokenAddress, toWalletAmount ), "the transfer of the base from the user to the TokenSwap SC failed" ); // send the quote to user require( _transferAmounts( wallet, msg.sender, quoteTokenAddress, toUserAmount ), "the transfer of the quote from the TokenSwap SC to the user failed" ); emit LogTokenSwap( msg.sender, baseTokenAddress, toWalletAmount, quoteTokenAddress, toUserAmount ); } return true; } /** * @dev Transfer amounts from user to this contract and vice versa. * @param _from The 'from' address. * @param _to The 'to' address. * @param _tokenAddress The asset to be transfer. * @param _amount The amount to be transfer. * @return bool. */ function _transferAmounts( address _from, address _to, address _tokenAddress, uint _amount ) private returns (bool) { if (isETH(_tokenAddress)) { if (_from == wallet) { require( IWallet(_from).transferAssetTo( _tokenAddress, _to, _amount ), "trasnsferAssetTo failed" ); } else { _to.transfer(_amount); } } else { if (_from == wallet) { require( IWallet(_from).transferAssetTo( _tokenAddress, _to, _amount ), "trasnsferAssetTo failed" ); } else { require( SafeTransfer._safeTransferFrom( _tokenAddress, _from, _to, _amount ), "transferFrom reserve to _receiver failed" ); } } return true; } }
TOD1
pragma solidity ^0.4.24; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/lifecycle/Destructible.sol /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } // File: zeppelin-solidity/contracts/ownership/Contactable.sol /** * @title Contactable token * @dev Basic version of a contactable contract, allowing the owner to provide a string with their * contact information. */ contract Contactable is Ownable{ string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param info The contact information to attach to the contract. */ function setContactInformation(string info) onlyOwner public { contactInformation = info; } } // File: contracts/Restricted.sol /** @title Restricted * Exposes onlyMonetha modifier */ contract Restricted is Ownable { //MonethaAddress set event event MonethaAddressSet( address _address, bool _isMonethaAddress ); mapping (address => bool) public isMonethaAddress; /** * Restrict methods in such way, that they can be invoked only by monethaAddress account. */ modifier onlyMonetha() { require(isMonethaAddress[msg.sender]); _; } /** * Allows owner to set new monetha address */ function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public { isMonethaAddress[_address] = _isMonethaAddress; MonethaAddressSet(_address, _isMonethaAddress); } } // File: contracts/ERC20.sol /** * @title ERC20 interface */ contract ERC20 { function totalSupply() public view returns (uint256); function decimals() public view returns(uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); // Return type not defined intentionally since not all ERC20 tokens return proper result type function transfer(address _to, uint256 _value) public; function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/MonethaGateway.sol /** * @title MonethaGateway * * MonethaGateway forward funds from order payment to merchant's wallet and collects Monetha fee. */ contract MonethaGateway is Pausable, Contactable, Destructible, Restricted { using SafeMath for uint256; string constant VERSION = "0.5"; /** * Fee permille of Monetha fee. * 1 permille (‰) = 0.1 percent (%) * 15‰ = 1.5% */ uint public constant FEE_PERMILLE = 15; /** * Address of Monetha Vault for fee collection */ address public monethaVault; /** * Account for permissions managing */ address public admin; event PaymentProcessedEther(address merchantWallet, uint merchantIncome, uint monethaIncome); event PaymentProcessedToken(address tokenAddress, address merchantWallet, uint merchantIncome, uint monethaIncome); /** * @param _monethaVault Address of Monetha Vault */ constructor(address _monethaVault, address _admin) public { require(_monethaVault != 0x0); monethaVault = _monethaVault; setAdmin(_admin); } /** * acceptPayment accept payment from PaymentAcceptor, forwards it to merchant's wallet * and collects Monetha fee. * @param _merchantWallet address of merchant's wallet for fund transfer * @param _monethaFee is a fee collected by Monetha */ function acceptPayment(address _merchantWallet, uint _monethaFee) external payable onlyMonetha whenNotPaused { require(_merchantWallet != 0x0); require(_monethaFee >= 0 && _monethaFee <= FEE_PERMILLE.mul(msg.value).div(1000)); // Monetha fee cannot be greater than 1.5% of payment uint merchantIncome = msg.value.sub(_monethaFee); _merchantWallet.transfer(merchantIncome); monethaVault.transfer(_monethaFee); emit PaymentProcessedEther(_merchantWallet, merchantIncome, _monethaFee); } /** * acceptTokenPayment accept token payment from PaymentAcceptor, forwards it to merchant's wallet * and collects Monetha fee. * @param _merchantWallet address of merchant's wallet for fund transfer * @param _monethaFee is a fee collected by Monetha * @param _tokenAddress is the token address * @param _value is the order value */ function acceptTokenPayment( address _merchantWallet, uint _monethaFee, address _tokenAddress, uint _value ) external onlyMonetha whenNotPaused { require(_merchantWallet != 0x0); // Monetha fee cannot be greater than 1.5% of payment require(_monethaFee >= 0 && _monethaFee <= FEE_PERMILLE.mul(_value).div(1000)); uint merchantIncome = _value.sub(_monethaFee); ERC20(_tokenAddress).transfer(_merchantWallet, merchantIncome); ERC20(_tokenAddress).transfer(monethaVault, _monethaFee); emit PaymentProcessedToken(_tokenAddress, _merchantWallet, merchantIncome, _monethaFee); } /** * changeMonethaVault allows owner to change address of Monetha Vault. * @param newVault New address of Monetha Vault */ function changeMonethaVault(address newVault) external onlyOwner whenNotPaused { monethaVault = newVault; } /** * Allows other monetha account or contract to set new monetha address */ function setMonethaAddress(address _address, bool _isMonethaAddress) public { require(msg.sender == admin || msg.sender == owner); isMonethaAddress[_address] = _isMonethaAddress; emit MonethaAddressSet(_address, _isMonethaAddress); } /** * setAdmin allows owner to change address of admin. * @param _admin New address of admin */ function setAdmin(address _admin) public onlyOwner { require(_admin != 0x0); admin = _admin; } } // File: contracts/MerchantDealsHistory.sol /** * @title MerchantDealsHistory * Contract stores hash of Deals conditions together with parties reputation for each deal * This history enables to see evolution of trust rating for both parties */ contract MerchantDealsHistory is Contactable, Restricted { string constant VERSION = "0.3"; /// Merchant identifier hash bytes32 public merchantIdHash; //Deal event event DealCompleted( uint orderId, address clientAddress, uint32 clientReputation, uint32 merchantReputation, bool successful, uint dealHash ); //Deal cancellation event event DealCancelationReason( uint orderId, address clientAddress, uint32 clientReputation, uint32 merchantReputation, uint dealHash, string cancelReason ); //Deal refund event event DealRefundReason( uint orderId, address clientAddress, uint32 clientReputation, uint32 merchantReputation, uint dealHash, string refundReason ); /** * @param _merchantId Merchant of the acceptor */ function MerchantDealsHistory(string _merchantId) public { require(bytes(_merchantId).length > 0); merchantIdHash = keccak256(_merchantId); } /** * recordDeal creates an event of completed deal * @param _orderId Identifier of deal's order * @param _clientAddress Address of client's account * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _isSuccess Identifies whether deal was successful or not * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) */ function recordDeal( uint _orderId, address _clientAddress, uint32 _clientReputation, uint32 _merchantReputation, bool _isSuccess, uint _dealHash) external onlyMonetha { DealCompleted( _orderId, _clientAddress, _clientReputation, _merchantReputation, _isSuccess, _dealHash ); } /** * recordDealCancelReason creates an event of not paid deal that was cancelled * @param _orderId Identifier of deal's order * @param _clientAddress Address of client's account * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) * @param _cancelReason deal cancelation reason (text) */ function recordDealCancelReason( uint _orderId, address _clientAddress, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash, string _cancelReason) external onlyMonetha { DealCancelationReason( _orderId, _clientAddress, _clientReputation, _merchantReputation, _dealHash, _cancelReason ); } /** * recordDealRefundReason creates an event of not paid deal that was cancelled * @param _orderId Identifier of deal's order * @param _clientAddress Address of client's account * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) * @param _refundReason deal refund reason (text) */ function recordDealRefundReason( uint _orderId, address _clientAddress, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash, string _refundReason) external onlyMonetha { DealRefundReason( _orderId, _clientAddress, _clientReputation, _merchantReputation, _dealHash, _refundReason ); } } // File: contracts/SafeDestructible.sol /** * @title SafeDestructible * Base contract that can be destroyed by owner. * Can be destructed if there are no funds on contract balance. */ contract SafeDestructible is Ownable { function destroy() onlyOwner public { require(this.balance == 0); selfdestruct(owner); } } // File: contracts/MerchantWallet.sol /** * @title MerchantWallet * Serves as a public Merchant profile with merchant profile info, * payment settings and latest reputation value. * Also MerchantWallet accepts payments for orders. */ contract MerchantWallet is Pausable, SafeDestructible, Contactable, Restricted { string constant VERSION = "0.5"; /// Address of merchant's account, that can withdraw from wallet address public merchantAccount; /// Address of merchant's fund address. address public merchantFundAddress; /// Unique Merchant identifier hash bytes32 public merchantIdHash; /// profileMap stores general information about the merchant mapping (string=>string) profileMap; /// paymentSettingsMap stores payment and order settings for the merchant mapping (string=>string) paymentSettingsMap; /// compositeReputationMap stores composite reputation, that compraises from several metrics mapping (string=>uint32) compositeReputationMap; /// number of last digits in compositeReputation for fractional part uint8 public constant REPUTATION_DECIMALS = 4; /** * Restrict methods in such way, that they can be invoked only by merchant account. */ modifier onlyMerchant() { require(msg.sender == merchantAccount); _; } /** * Fund Address should always be Externally Owned Account and not a contract. */ modifier isEOA(address _fundAddress) { uint256 _codeLength; assembly {_codeLength := extcodesize(_fundAddress)} require(_codeLength == 0, "sorry humans only"); _; } /** * Restrict methods in such way, that they can be invoked only by merchant account or by monethaAddress account. */ modifier onlyMerchantOrMonetha() { require(msg.sender == merchantAccount || isMonethaAddress[msg.sender]); _; } /** * @param _merchantAccount Address of merchant's account, that can withdraw from wallet * @param _merchantId Merchant identifier * @param _fundAddress Merchant's fund address, where amount will be transferred. */ constructor(address _merchantAccount, string _merchantId, address _fundAddress) public isEOA(_fundAddress) { require(_merchantAccount != 0x0); require(bytes(_merchantId).length > 0); merchantAccount = _merchantAccount; merchantIdHash = keccak256(_merchantId); merchantFundAddress = _fundAddress; } /** * Accept payment from MonethaGateway */ function () external payable { } /** * @return profile info by string key */ function profile(string key) external constant returns (string) { return profileMap[key]; } /** * @return payment setting by string key */ function paymentSettings(string key) external constant returns (string) { return paymentSettingsMap[key]; } /** * @return composite reputation value by string key */ function compositeReputation(string key) external constant returns (uint32) { return compositeReputationMap[key]; } /** * Set profile info by string key */ function setProfile( string profileKey, string profileValue, string repKey, uint32 repValue ) external onlyOwner { profileMap[profileKey] = profileValue; if (bytes(repKey).length != 0) { compositeReputationMap[repKey] = repValue; } } /** * Set payment setting by string key */ function setPaymentSettings(string key, string value) external onlyOwner { paymentSettingsMap[key] = value; } /** * Set composite reputation value by string key */ function setCompositeReputation(string key, uint32 value) external onlyMonetha { compositeReputationMap[key] = value; } /** * Allows withdrawal of funds to beneficiary address */ function doWithdrawal(address beneficiary, uint amount) private { require(beneficiary != 0x0); beneficiary.transfer(amount); } /** * Allows merchant to withdraw funds to beneficiary address */ function withdrawTo(address beneficiary, uint amount) public onlyMerchant whenNotPaused { doWithdrawal(beneficiary, amount); } /** * Allows merchant to withdraw funds to it's own account */ function withdraw(uint amount) external onlyMerchant { withdrawTo(msg.sender, amount); } /** * Allows merchant or Monetha to initiate exchange of funds by withdrawing funds to deposit address of the exchange */ function withdrawToExchange(address depositAccount, uint amount) external onlyMerchantOrMonetha whenNotPaused { doWithdrawal(depositAccount, amount); } /** * Allows merchant or Monetha to initiate exchange of funds by withdrawing all funds to deposit address of the exchange */ function withdrawAllToExchange(address depositAccount, uint min_amount) external onlyMerchantOrMonetha whenNotPaused { require (address(this).balance >= min_amount); doWithdrawal(depositAccount, address(this).balance); } /** * Allows merchant or Monetha to initiate exchange of tokens by withdrawing all tokens to deposit address of the exchange */ function withdrawAllTokensToExchange(address _tokenAddress, address _depositAccount, uint _minAmount) external onlyMerchantOrMonetha whenNotPaused { require(_tokenAddress != address(0)); uint balance = ERC20(_tokenAddress).balanceOf(address(this)); require(balance >= _minAmount); ERC20(_tokenAddress).transfer(_depositAccount, balance); } /** * Allows merchant to change it's account address */ function changeMerchantAccount(address newAccount) external onlyMerchant whenNotPaused { merchantAccount = newAccount; } /** * Allows merchant to change it's fund address. */ function changeFundAddress(address newFundAddress) external onlyMerchant isEOA(newFundAddress) { merchantFundAddress = newFundAddress; } } // File: contracts/PaymentProcessor.sol /** * @title PaymentProcessor * Each Merchant has one PaymentProcessor that ensure payment and order processing with Trust and Reputation * * Payment Processor State Transitions: * Null -(addOrder) -> Created * Created -(securePay) -> Paid * Created -(cancelOrder) -> Cancelled * Paid -(refundPayment) -> Refunding * Paid -(processPayment) -> Finalized * Refunding -(withdrawRefund) -> Refunded */ contract PaymentProcessor is Pausable, Destructible, Contactable, Restricted { using SafeMath for uint256; string constant VERSION = "0.6"; /** * Fee permille of Monetha fee. * 1 permille = 0.1 % * 15 permille = 1.5% */ uint public constant FEE_PERMILLE = 15; /// MonethaGateway contract for payment processing MonethaGateway public monethaGateway; /// MerchantDealsHistory contract of acceptor's merchant MerchantDealsHistory public merchantHistory; /// Address of MerchantWallet, where merchant reputation and funds are stored MerchantWallet public merchantWallet; /// Merchant identifier hash, that associates with the acceptor bytes32 public merchantIdHash; enum State {Null, Created, Paid, Finalized, Refunding, Refunded, Cancelled} struct Order { State state; uint price; uint fee; address paymentAcceptor; address originAddress; address tokenAddress; } mapping (uint=>Order) public orders; /** * Asserts current state. * @param _state Expected state * @param _orderId Order Id */ modifier atState(uint _orderId, State _state) { require(_state == orders[_orderId].state); _; } /** * Performs a transition after function execution. * @param _state Next state * @param _orderId Order Id */ modifier transition(uint _orderId, State _state) { _; orders[_orderId].state = _state; } /** * payment Processor sets Monetha Gateway * @param _merchantId Merchant of the acceptor * @param _merchantHistory Address of MerchantDealsHistory contract of acceptor's merchant * @param _monethaGateway Address of MonethaGateway contract for payment processing * @param _merchantWallet Address of MerchantWallet, where merchant reputation and funds are stored */ constructor( string _merchantId, MerchantDealsHistory _merchantHistory, MonethaGateway _monethaGateway, MerchantWallet _merchantWallet ) public { require(bytes(_merchantId).length > 0); merchantIdHash = keccak256(_merchantId); setMonethaGateway(_monethaGateway); setMerchantWallet(_merchantWallet); setMerchantDealsHistory(_merchantHistory); } /** * Assigns the acceptor to the order (when client initiates order). * @param _orderId Identifier of the order * @param _price Price of the order * @param _paymentAcceptor order payment acceptor * @param _originAddress buyer address * @param _fee Monetha fee */ function addOrder( uint _orderId, uint _price, address _paymentAcceptor, address _originAddress, uint _fee, address _tokenAddress ) external whenNotPaused atState(_orderId, State.Null) { require(_orderId > 0); require(_price > 0); require(_fee >= 0 && _fee <= FEE_PERMILLE.mul(_price).div(1000)); // Monetha fee cannot be greater than 1.5% of price require(_paymentAcceptor != address(0)); require(_originAddress != address(0)); require(orders[_orderId].price == 0 && orders[_orderId].fee == 0); orders[_orderId] = Order({ state: State.Created, price: _price, fee: _fee, paymentAcceptor: _paymentAcceptor, originAddress: _originAddress, tokenAddress: _tokenAddress }); } /** * securePay can be used by client if he wants to securely set client address for refund together with payment. * This function require more gas, then fallback function. * @param _orderId Identifier of the order */ function securePay(uint _orderId) external payable whenNotPaused atState(_orderId, State.Created) transition(_orderId, State.Paid) { Order storage order = orders[_orderId]; require(msg.sender == order.paymentAcceptor); require(msg.value == order.price); } /** * secureTokenPay can be used by client if he wants to securely set client address for token refund together with token payment. * This call requires that token's approve method has been called prior to this. * @param _orderId Identifier of the order */ function secureTokenPay(uint _orderId) external whenNotPaused atState(_orderId, State.Created) transition(_orderId, State.Paid) { Order storage order = orders[_orderId]; require(msg.sender == order.paymentAcceptor); require(order.tokenAddress != address(0)); ERC20(order.tokenAddress).transferFrom(msg.sender, address(this), order.price); } /** * cancelOrder is used when client doesn't pay and order need to be cancelled. * @param _orderId Identifier of the order * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) * @param _cancelReason Order cancel reason */ function cancelOrder( uint _orderId, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash, string _cancelReason ) external onlyMonetha whenNotPaused atState(_orderId, State.Created) transition(_orderId, State.Cancelled) { require(bytes(_cancelReason).length > 0); Order storage order = orders[_orderId]; updateDealConditions( _orderId, _clientReputation, _merchantReputation, false, _dealHash ); merchantHistory.recordDealCancelReason( _orderId, order.originAddress, _clientReputation, _merchantReputation, _dealHash, _cancelReason ); } /** * refundPayment used in case order cannot be processed. * This function initiate process of funds refunding to the client. * @param _orderId Identifier of the order * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) * @param _refundReason Order refund reason, order will be moved to State Cancelled after Client withdraws money */ function refundPayment( uint _orderId, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash, string _refundReason ) external onlyMonetha whenNotPaused atState(_orderId, State.Paid) transition(_orderId, State.Refunding) { require(bytes(_refundReason).length > 0); Order storage order = orders[_orderId]; updateDealConditions( _orderId, _clientReputation, _merchantReputation, false, _dealHash ); merchantHistory.recordDealRefundReason( _orderId, order.originAddress, _clientReputation, _merchantReputation, _dealHash, _refundReason ); } /** * withdrawRefund performs fund transfer to the client's account. * @param _orderId Identifier of the order */ function withdrawRefund(uint _orderId) external whenNotPaused atState(_orderId, State.Refunding) transition(_orderId, State.Refunded) { Order storage order = orders[_orderId]; order.originAddress.transfer(order.price); } /** * withdrawTokenRefund performs token transfer to the client's account. * @param _orderId Identifier of the order */ function withdrawTokenRefund(uint _orderId) external whenNotPaused atState(_orderId, State.Refunding) transition(_orderId, State.Refunded) { require(orders[_orderId].tokenAddress != address(0)); ERC20(orders[_orderId].tokenAddress).transfer(orders[_orderId].originAddress, orders[_orderId].price); } /** * processPayment transfer funds/tokens to MonethaGateway and completes the order. * @param _orderId Identifier of the order * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) */ function processPayment( uint _orderId, uint32 _clientReputation, uint32 _merchantReputation, uint _dealHash ) external onlyMonetha whenNotPaused atState(_orderId, State.Paid) transition(_orderId, State.Finalized) { address fundAddress; fundAddress = merchantWallet.merchantFundAddress(); if (orders[_orderId].tokenAddress != address(0)) { if (fundAddress != address(0)) { ERC20(orders[_orderId].tokenAddress).transfer(address(monethaGateway), orders[_orderId].price); monethaGateway.acceptTokenPayment(fundAddress, orders[_orderId].fee, orders[_orderId].tokenAddress, orders[_orderId].price); } else { ERC20(orders[_orderId].tokenAddress).transfer(address(monethaGateway), orders[_orderId].price); monethaGateway.acceptTokenPayment(merchantWallet, orders[_orderId].fee, orders[_orderId].tokenAddress, orders[_orderId].price); } } else { if (fundAddress != address(0)) { monethaGateway.acceptPayment.value(orders[_orderId].price)(fundAddress, orders[_orderId].fee); } else { monethaGateway.acceptPayment.value(orders[_orderId].price)(merchantWallet, orders[_orderId].fee); } } updateDealConditions( _orderId, _clientReputation, _merchantReputation, true, _dealHash ); } /** * setMonethaGateway allows owner to change address of MonethaGateway. * @param _newGateway Address of new MonethaGateway contract */ function setMonethaGateway(MonethaGateway _newGateway) public onlyOwner { require(address(_newGateway) != 0x0); monethaGateway = _newGateway; } /** * setMerchantWallet allows owner to change address of MerchantWallet. * @param _newWallet Address of new MerchantWallet contract */ function setMerchantWallet(MerchantWallet _newWallet) public onlyOwner { require(address(_newWallet) != 0x0); require(_newWallet.merchantIdHash() == merchantIdHash); merchantWallet = _newWallet; } /** * setMerchantDealsHistory allows owner to change address of MerchantDealsHistory. * @param _merchantHistory Address of new MerchantDealsHistory contract */ function setMerchantDealsHistory(MerchantDealsHistory _merchantHistory) public onlyOwner { require(address(_merchantHistory) != 0x0); require(_merchantHistory.merchantIdHash() == merchantIdHash); merchantHistory = _merchantHistory; } /** * updateDealConditions record finalized deal and updates merchant reputation * in future: update Client reputation * @param _orderId Identifier of the order * @param _clientReputation Updated reputation of the client * @param _merchantReputation Updated reputation of the merchant * @param _isSuccess Identifies whether deal was successful or not * @param _dealHash Hashcode of the deal, describing the order (used for deal verification) */ function updateDealConditions( uint _orderId, uint32 _clientReputation, uint32 _merchantReputation, bool _isSuccess, uint _dealHash ) internal { merchantHistory.recordDeal( _orderId, orders[_orderId].originAddress, _clientReputation, _merchantReputation, _isSuccess, _dealHash ); //update parties Reputation merchantWallet.setCompositeReputation("total", _merchantReputation); } }
TOD1
pragma solidity ^0.4.13; // ---------------------------------------------------------------------------------------------- // Special coin of Midnighters Club Facebook community // https://facebook.com/theMidnightersClub/ // ---------------------------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 contract ERC20 { // Get the total token supply function totalSupply() constant returns (uint256 totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) returns (bool success); // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract MidnightCoin is ERC20, Owned { string public constant symbol = "MNC"; string public constant name = "Midnight Coin"; uint8 public constant decimals = 18; uint256 _totalSupply = 100000000000000000000; uint public constant FREEZE_PERIOD = 1 years; uint public crowdSaleStartTimestamp; string public lastLoveLetter = ""; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // Constructor function MidnightCoin() { owner = msg.sender; balances[owner] = 1000000000000000000; crowdSaleStartTimestamp = now + 7 days; } function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } // What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // features function kill() onlyOwner { selfdestruct(owner); } function withdraw() public onlyOwner { require( _totalSupply == 0 ); owner.transfer(this.balance); } function buyMNC(string _loveletter) payable{ require (now > crowdSaleStartTimestamp); require( _totalSupply >= msg.value); balances[msg.sender] += msg.value; _totalSupply -= msg.value; lastLoveLetter = _loveletter; } function sellMNC(uint256 _amount) { require (now > crowdSaleStartTimestamp + FREEZE_PERIOD); require( balances[msg.sender] >= _amount); balances[msg.sender] -= _amount; _totalSupply += _amount; msg.sender.transfer(_amount); } function() payable{ buyMNC("Hi! I am anonymous holder"); } }
TOD1
pragma solidity ^0.4.23; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface TokenContract { function transfer(address _recipient, uint256 _amount) external returns (bool); function balanceOf(address _holder) external view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); } contract Exchange is Ownable { using SafeMath for uint256; uint256 public buyPrice; uint256 public sellPrice; address public tokenAddress; uint256 private fullEther = 1 ether; constructor() public { buyPrice = 600; sellPrice = 400; tokenAddress = 0x0; } function setBuyPrice(uint256 _price) onlyOwner public { buyPrice = _price; } function setSellPrice(uint256 _price) onlyOwner public { sellPrice = _price; } function() payable public { sellTokens(); } function sellTokens() payable public { TokenContract tkn = TokenContract(tokenAddress); uint256 tokensToSell = msg.value.mul(sellPrice); require(tkn.balanceOf(address(this)) >= tokensToSell); tkn.transfer(msg.sender, tokensToSell); emit SellTransaction(msg.value, tokensToSell); } function buyTokens(uint256 _amount) public { address seller = msg.sender; TokenContract tkn = TokenContract(tokenAddress); uint256 transactionPrice = _amount.div(buyPrice); require (address(this).balance >= transactionPrice); require (tkn.transferFrom(msg.sender, address(this), _amount)); seller.transfer(transactionPrice); emit BuyTransaction(transactionPrice, _amount); } function getBalance(uint256 _amount) onlyOwner public { msg.sender.transfer(_amount); } function getTokens(uint256 _amount) onlyOwner public { TokenContract tkn = TokenContract(tokenAddress); tkn.transfer(msg.sender, _amount); } function killMe() onlyOwner public { TokenContract tkn = TokenContract(tokenAddress); uint256 tokensLeft = tkn.balanceOf(address(this)); tkn.transfer(msg.sender, tokensLeft); msg.sender.transfer(address(this).balance); selfdestruct(owner); } function changeToken(address _address) onlyOwner public { tokenAddress = _address; } event SellTransaction(uint256 ethAmount, uint256 tokenAmount); event BuyTransaction(uint256 ethAmount, uint256 tokenAmount); }
TOD1
pragma solidity ^0.4.20; contract BLITZ_GAME { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>3 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function set_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.20; contract Win_Some_Ether { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 3 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function init_quiz_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
/* file: VentanaToken.sol ver: 0.1.0 author: Darryl Morris date: 14-Aug-2017 email: o0ragman0o AT gmail.com (c) Darryl Morris 2017 A collated contract set for a token sale specific to the requirments of Veredictum's Ventana token product. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See MIT Licence for further details. <https://opensource.org/licenses/MIT>. Release Notes ------------- 0.1.0 * Release version * updated owner, fundWallet, USD_PER_ETH, and START_DATE to final values in VentanaTokenConfig */ pragma solidity ^0.4.13; /*-----------------------------------------------------------------------------\ Ventana token sale configuration \*----------------------------------------------------------------------------*/ // Contains token sale parameters contract VentanaTokenConfig { // ERC20 trade name and symbol string public name = "Ventana"; string public symbol = "VNT"; // Owner has power to abort, discount addresses, sweep successful funds, // change owner, sweep alien tokens. address public owner = 0xF4b087Ad256ABC5BE11E0433B15Ed012c8AEC8B4; // veredictumPrimary address checksummed // Fund wallet should also be audited prior to deployment // NOTE: Must be checksummed address! address public fundWallet = 0xd6514387236595e080B97c8ead1cBF12f9a6Ab65; // multiSig address checksummed // Tokens awarded per USD contributed uint public constant TOKENS_PER_USD = 3; // Ether market price in USD uint public constant USD_PER_ETH = 258; // calculated from 60 day moving average as at 14th August 2017 // Minimum and maximum target in USD uint public constant MIN_USD_FUND = 2000000; // $2m uint public constant MAX_USD_FUND = 20000000; // $20m // Non-KYC contribution limit in USD uint public constant KYC_USD_LMT = 10000; // There will be exactly 300,000,000 tokens regardless of number sold // Unsold tokens are put into the Strategic Growth token pool uint public constant MAX_TOKENS = 300000000; // Funding begins on 14th August 2017 // `+ new Date('19:00 14 August 2017')/1000` uint public constant START_DATE = 1502701200; // Mon Aug 14 2017 19:00:00 GMT+1000 (AEST) // Period for fundraising uint public constant FUNDING_PERIOD = 28 days; } library SafeMath { // a add to b function add(uint a, uint b) internal returns (uint c) { c = a + b; assert(c >= a); } // a subtract b function sub(uint a, uint b) internal returns (uint c) { c = a - b; assert(c <= a); } // a multiplied by b function mul(uint a, uint b) internal returns (uint c) { c = a * b; assert(a == 0 || c / a == b); } // a divided by b function div(uint a, uint b) internal returns (uint c) { c = a / b; // No assert required as no overflows are posible. } } contract ReentryProtected { // The reentry protection state mutex. bool __reMutex; // Sets and resets mutex in order to block functin reentry modifier preventReentry() { require(!__reMutex); __reMutex = true; _; delete __reMutex; } // Blocks function entry if mutex is set modifier noReentry() { require(!__reMutex); _; } } contract ERC20Token { using SafeMath for uint; /* Constants */ // none /* State variable */ /// @return The Total supply of tokens uint public totalSupply; /// @return Token symbol string public symbol; // Token ownership mapping mapping (address => uint) balances; // Allowances mapping mapping (address => mapping (address => uint)) allowed; /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed _from, address indexed _to, uint256 _amount); // Triggered whenever approve(address _spender, uint256 _amount) is called. event Approval( address indexed _owner, address indexed _spender, uint256 _amount); /* Modifiers */ // none /* Functions */ // Using an explicit getter allows for function overloading function balanceOf(address _addr) public constant returns (uint) { return balances[_addr]; } // Using an explicit getter allows for function overloading function allowance(address _owner, address _spender) public constant returns (uint) { return allowed[_owner][_spender]; } // Send _value amount of tokens to address _to function transfer(address _to, uint256 _amount) public returns (bool) { return xfer(msg.sender, _to, _amount); } // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_amount <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); return xfer(_from, _to, _amount); } // Process a transfer internally. function xfer(address _from, address _to, uint _amount) internal returns (bool) { require(_amount <= balances[_from]); Transfer(_from, _to, _amount); // avoid wasting gas on 0 token transfers if(_amount == 0) return true; balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); return true; } // Approves a third-party spender function approve(address _spender, uint256 _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } } /*-----------------------------------------------------------------------------\ ## Conditional Entry Table Functions must throw on F conditions Conditional Entry Table (functions must throw on F conditions) renetry prevention on all public mutating functions Reentry mutex set in moveFundsToWallet(), refund() |function |<START_DATE|<END_DATE |fundFailed |fundSucceeded|icoSucceeded |------------------------|:---------:|:--------:|:----------:|:-----------:|:---------:| |() |KYC |T |F |T |F | |abort() |T |T |T |T |F | |proxyPurchase() |KYC |T |F |T |F | |addKycAddress() |T |T |F |T |T | |finaliseICO() |F |F |F |T |T | |refund() |F |F |T |F |F | |transfer() |F |F |F |F |T | |transferFrom() |F |F |F |F |T | |approve() |F |F |F |F |T | |changeOwner() |T |T |T |T |T | |acceptOwnership() |T |T |T |T |T | |changeVeredictum() |T |T |T |T |T | |destroy() |F |F |!__abortFuse|F |F | |transferAnyERC20Tokens()|T |T |T |T |T | \*----------------------------------------------------------------------------*/ contract VentanaTokenAbstract { // TODO comment events event KYCAddress(address indexed _addr, bool indexed _kyc); event Refunded(address indexed _addr, uint indexed _value); event ChangedOwner(address indexed _from, address indexed _to); event ChangeOwnerTo(address indexed _to); event FundsTransferred(address indexed _wallet, uint indexed _value); // This fuse blows upon calling abort() which forces a fail state bool public __abortFuse = true; // Set to true after the fund is swept to the fund wallet, allows token // transfers and prevents abort() bool public icoSuccessful; // Token conversion factors are calculated with decimal places at parity with ether uint8 public constant decimals = 18; // An address authorised to take ownership address public newOwner; // The Veredictum smart contract address address public veredictum; // Total ether raised during funding uint public etherRaised; // Preauthorized tranch discount addresses // holder => discount mapping (address => bool) public kycAddresses; // Record of ether paid per address mapping (address => uint) public etherContributed; // Return `true` if MIN_FUNDS were raised function fundSucceeded() public constant returns (bool); // Return `true` if MIN_FUNDS were not raised before END_DATE function fundFailed() public constant returns (bool); // Returns USD raised for set ETH/USD rate function usdRaised() public constant returns (uint); // Returns an amount in eth equivilent to USD at the set rate function usdToEth(uint) public constant returns(uint); // Returns the USD value of ether at the set USD/ETH rate function ethToUsd(uint _wei) public constant returns (uint); // Returns token/ether conversion given ether value and address. function ethToTokens(uint _eth) public constant returns (uint); // Processes a token purchase for a given address function proxyPurchase(address _addr) payable returns (bool); // Owner can move funds of successful fund to fundWallet function finaliseICO() public returns (bool); // Registers a discounted address function addKycAddress(address _addr, bool _kyc) public returns (bool); // Refund on failed or aborted sale function refund(address _addr) public returns (bool); // To cancel token sale prior to START_DATE function abort() public returns (bool); // Change the Veredictum backend contract address function changeVeredictum(address _addr) public returns (bool); // For owner to salvage tokens sent to contract function transferAnyERC20Token(address tokenAddress, uint amount) returns (bool); } /*-----------------------------------------------------------------------------\ Ventana token implimentation \*----------------------------------------------------------------------------*/ contract VentanaToken is ReentryProtected, ERC20Token, VentanaTokenAbstract, VentanaTokenConfig { using SafeMath for uint; // // Constants // // USD to ether conversion factors calculated from `VentanaTokenConfig` constants uint public constant TOKENS_PER_ETH = TOKENS_PER_USD * USD_PER_ETH; uint public constant MIN_ETH_FUND = 1 ether * MIN_USD_FUND / USD_PER_ETH; uint public constant MAX_ETH_FUND = 1 ether * MAX_USD_FUND / USD_PER_ETH; uint public constant KYC_ETH_LMT = 1 ether * KYC_USD_LMT / USD_PER_ETH; // General funding opens LEAD_IN_PERIOD after deployment (timestamps can't be constant) uint public END_DATE = START_DATE + FUNDING_PERIOD; // // Modifiers // modifier onlyOwner { require(msg.sender == owner); _; } // // Functions // // Constructor function VentanaToken() { // ICO parameters are set in VentanaTSConfig // Invalid configuration catching here require(bytes(symbol).length > 0); require(bytes(name).length > 0); require(owner != 0x0); require(fundWallet != 0x0); require(TOKENS_PER_USD > 0); require(USD_PER_ETH > 0); require(MIN_USD_FUND > 0); require(MAX_USD_FUND > MIN_USD_FUND); require(START_DATE > 0); require(FUNDING_PERIOD > 0); // Setup and allocate token supply to 18 decimal places totalSupply = MAX_TOKENS * 1e18; balances[fundWallet] = totalSupply; Transfer(0x0, fundWallet, totalSupply); } // Default function function () payable { // Pass through to purchasing function. Will throw on failed or // successful ICO proxyPurchase(msg.sender); } // // Getters // // ICO fails if aborted or minimum funds are not raised by the end date function fundFailed() public constant returns (bool) { return !__abortFuse || (now > END_DATE && etherRaised < MIN_ETH_FUND); } // Funding succeeds if not aborted, minimum funds are raised before end date function fundSucceeded() public constant returns (bool) { return !fundFailed() && etherRaised >= MIN_ETH_FUND; } // Returns the USD value of ether at the set USD/ETH rate function ethToUsd(uint _wei) public constant returns (uint) { return USD_PER_ETH.mul(_wei).div(1 ether); } // Returns the ether value of USD at the set USD/ETH rate function usdToEth(uint _usd) public constant returns (uint) { return _usd.mul(1 ether).div(USD_PER_ETH); } // Returns the USD value of ether raised at the set USD/ETH rate function usdRaised() public constant returns (uint) { return ethToUsd(etherRaised); } // Returns the number of tokens for given amount of ether for an address function ethToTokens(uint _wei) public constant returns (uint) { uint usd = ethToUsd(_wei); // Percent bonus funding tiers for USD funding uint bonus = usd >= 2000000 ? 35 : usd >= 500000 ? 30 : usd >= 100000 ? 20 : usd >= 25000 ? 15 : usd >= 10000 ? 10 : usd >= 5000 ? 5 : 0; // using n.2 fixed point decimal for whole number percentage. return _wei.mul(TOKENS_PER_ETH).mul(bonus + 100).div(100); } // // ICO functions // // The fundraising can be aborted any time before funds are swept to the // fundWallet. // This will force a fail state and allow refunds to be collected. function abort() public noReentry onlyOwner returns (bool) { require(!icoSuccessful); delete __abortFuse; return true; } // General addresses can purchase tokens during funding function proxyPurchase(address _addr) payable noReentry returns (bool) { require(!fundFailed()); require(!icoSuccessful); require(now <= END_DATE); require(msg.value > 0); // Non-KYC'ed funders can only contribute up to $10000 after prefund period if(!kycAddresses[_addr]) { require(now >= START_DATE); require((etherContributed[_addr].add(msg.value)) <= KYC_ETH_LMT); } // Get ether to token conversion uint tokens = ethToTokens(msg.value); // transfer tokens from fund wallet xfer(fundWallet, _addr, tokens); // Update holder payments etherContributed[_addr] = etherContributed[_addr].add(msg.value); // Update funds raised etherRaised = etherRaised.add(msg.value); // Bail if this pushes the fund over the USD cap or Token cap require(etherRaised <= MAX_ETH_FUND); return true; } // Owner can KYC (or revoke) addresses until close of funding function addKycAddress(address _addr, bool _kyc) public noReentry onlyOwner returns (bool) { require(!fundFailed()); kycAddresses[_addr] = _kyc; KYCAddress(_addr, _kyc); return true; } // Owner can sweep a successful funding to the fundWallet // Contract can be aborted up until this action. function finaliseICO() public onlyOwner preventReentry() returns (bool) { require(fundSucceeded()); icoSuccessful = true; FundsTransferred(fundWallet, this.balance); fundWallet.transfer(this.balance); return true; } // Refunds can be claimed from a failed ICO function refund(address _addr) public preventReentry() returns (bool) { require(fundFailed()); uint value = etherContributed[_addr]; // Transfer tokens back to origin // (Not really necessary but looking for graceful exit) xfer(_addr, fundWallet, balances[_addr]); // garbage collect delete etherContributed[_addr]; delete kycAddresses[_addr]; Refunded(_addr, value); if (value > 0) { _addr.transfer(value); } return true; } // // ERC20 overloaded functions // function transfer(address _to, uint _amount) public preventReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.transfer(_to, _amount); if (_to == veredictum) // Notify the Veredictum contract it has been sent tokens require(Notify(veredictum).notify(msg.sender, _amount)); return true; } function transferFrom(address _from, address _to, uint _amount) public preventReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.transferFrom(_from, _to, _amount); if (_to == veredictum) // Notify the Veredictum contract it has been sent tokens require(Notify(veredictum).notify(msg.sender, _amount)); return true; } function approve(address _spender, uint _amount) public noReentry returns (bool) { // ICO must be successful require(icoSuccessful); super.approve(_spender, _amount); return true; } // // Contract managment functions // // To initiate an ownership change function changeOwner(address _newOwner) public noReentry onlyOwner returns (bool) { ChangeOwnerTo(_newOwner); newOwner = _newOwner; return true; } // To accept ownership. Required to prove new address can call the contract. function acceptOwnership() public noReentry returns (bool) { require(msg.sender == newOwner); ChangedOwner(owner, newOwner); owner = newOwner; return true; } // Change the address of the Veredictum contract address. The contract // must impliment the `Notify` interface. function changeVeredictum(address _addr) public noReentry onlyOwner returns (bool) { veredictum = _addr; return true; } // The contract can be selfdestructed after abort and ether balance is 0. function destroy() public noReentry onlyOwner { require(!__abortFuse); require(this.balance == 0); selfdestruct(owner); } // Owner can salvage ERC20 tokens that may have been sent to the account function transferAnyERC20Token(address tokenAddress, uint amount) public onlyOwner preventReentry returns (bool) { require(ERC20Token(tokenAddress).transfer(owner, amount)); return true; } } interface Notify { event Notified(address indexed _from, uint indexed _amount); function notify(address _from, uint _amount) public returns (bool); } contract VeredictumTest is Notify { address public vnt; function setVnt(address _addr) { vnt = _addr; } function notify(address _from, uint _amount) public returns (bool) { require(msg.sender == vnt); Notified(_from, _amount); return true; } }
TOD1
pragma solidity ^0.4.20; contract PAY_FOR_ANSWER { function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.25; contract ArceonMoneyNetwork { using SafeMath for uint256; address public owner; address parentUser; address[] users; mapping(address => bool) usersExist; mapping(address => address) users2users; mapping(address => uint256) balances; mapping(address => uint256) balancesTotal; uint256 nextUserId = 0; uint256 cyles = 5; constructor() public {owner = msg.sender; } modifier onlyOwner {if (msg.sender == owner) _;} event Register(address indexed user, address indexed parentUser); event BalanceUp(address indexed user, uint256 amount); event ReferalBonus(address indexed user, uint256 amount); event TransferMyMoney(address user, uint256 amount); function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } function () payable public{ parentUser = bytesToAddress(msg.data); if (msg.value==0){ transferMyMoney(); return;} require(msg.value == 50 finney); require(msg.sender != address(0)); require(parentUser != address(0)); require(!usersExist[msg.sender]); _register(msg.sender, msg.value); } function _register(address user, uint256 amount) internal { if (users.length > 0) { require(parentUser!=user); require(usersExist[parentUser]); } if (users.length ==0) {users2users[parentUser]=parentUser;} users.push(user); usersExist[user]=true; users2users[user]=parentUser; emit Register(user, parentUser); uint256 referalBonus = amount.div(2); if (cyles==0) {referalBonus = amount;} //we exclude a money wave balances[parentUser] = balances[parentUser].add(referalBonus.div(2)); balancesTotal[parentUser] = balancesTotal[parentUser].add(referalBonus.div(2)); emit ReferalBonus(parentUser, referalBonus.div(2)); balances[users2users[parentUser]] = balances[users2users[parentUser]].add(referalBonus.div(2)); balancesTotal[users2users[parentUser]] = balancesTotal[users2users[parentUser]].add(referalBonus.div(2)); emit ReferalBonus(users2users[parentUser], referalBonus.div(2)); uint256 length = users.length; uint256 existLastIndex = length.sub(1); //we exclude a money wave if (cyles!=0){ for (uint i = 1; i <= cyles; i++) { nextUserId = nextUserId.add(1); if(nextUserId > existLastIndex){ nextUserId = 0;} balances[users[nextUserId]] = balances[users[nextUserId]].add(referalBonus.div(cyles)); balancesTotal[users[nextUserId]] = balancesTotal[users[nextUserId]].add(referalBonus.div(cyles)); emit BalanceUp(users[nextUserId], referalBonus.div(cyles)); } } //we exclude a money wave } function transferMyMoney() public { require(balances[msg.sender]>0); msg.sender.transfer(balances[msg.sender]); emit TransferMyMoney(msg.sender, balances[msg.sender]); balances[msg.sender]=0; } function ViewRealBalance(address input) public view returns (uint256 balanceReal) { balanceReal= balances[input]; balanceReal=balanceReal.div(1000000000000); return balanceReal; } function ViewTotalBalance(address input) public view returns (uint256 balanceTotal) { balanceTotal=balancesTotal [input]; balanceTotal=balanceTotal.div(1000000000000); return balanceTotal; } function viewBlockchainArceonMoneyNetwork(uint256 id) public view returns (address userAddress) { return users[id]; } function CirclePoints() public view returns (uint256 CirclePoint) { CirclePoint = nextUserId; return CirclePoint; } function NumberUser() public view returns (uint256 numberOfUser) { numberOfUser = users.length; return numberOfUser; } function LenCyless() public view returns (uint256 LenCyles) { LenCyles = cyles; return LenCyles; } function newCyles(uint256 _newCyles) external onlyOwner { cyles = _newCyles; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } }
TOD1
pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/examples/SimpleToken.sol /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract SimpleToken is StandardToken { string public constant name = "SimpleToken"; // solium-disable-line uppercase string public constant symbol = "SIM"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ function SimpleToken() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/LockedOutTokens.sol // for unit test purposes only contract LockedOutTokens is Ownable { address public wallet; uint8 public tranchesCount; uint256 public trancheSize; uint256 public period; uint256 public startTimestamp; uint8 public tranchesPayedOut = 0; ERC20Basic internal token; function LockedOutTokens( address _wallet, address _tokenAddress, uint256 _startTimestamp, uint8 _tranchesCount, uint256 _trancheSize, uint256 _periodSeconds ) { require(_wallet != address(0)); require(_tokenAddress != address(0)); require(_startTimestamp > 0); require(_tranchesCount > 0); require(_trancheSize > 0); require(_periodSeconds > 0); wallet = _wallet; tranchesCount = _tranchesCount; startTimestamp = _startTimestamp; trancheSize = _trancheSize; period = _periodSeconds; token = ERC20Basic(_tokenAddress); } function grant() public { require(wallet == msg.sender); require(tranchesPayedOut < tranchesCount); require(startTimestamp > 0); require(now >= startTimestamp + (period * (tranchesPayedOut + 1))); tranchesPayedOut = tranchesPayedOut + 1; token.transfer(wallet, trancheSize); } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: contracts/TiqpitToken.sol contract TiqpitToken is StandardToken, Pausable { using SafeMath for uint256; string constant public name = "Tiqpit Token"; string constant public symbol = "PIT"; uint8 constant public decimals = 18; string constant public smallestUnitName = "TIQ"; uint256 constant public INITIAL_TOTAL_SUPPLY = 500e6 * (uint256(10) ** decimals); address private addressIco; modifier onlyIco() { require(msg.sender == addressIco); _; } /** * @dev Create TiqpitToken contract and set pause * @param _ico The address of ICO contract. */ function TiqpitToken (address _ico) public { require(_ico != address(0)); addressIco = _ico; totalSupply_ = totalSupply_.add(INITIAL_TOTAL_SUPPLY); balances[_ico] = balances[_ico].add(INITIAL_TOTAL_SUPPLY); Transfer(address(0), _ico, INITIAL_TOTAL_SUPPLY); pause(); } /** * @dev Transfer token for a specified address with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) whenNotPaused public returns (bool) { super.transferFrom(_from, _to, _value); } /** * @dev Transfer tokens from ICO address to another address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) { super.transfer(_to, _value); } /** * @dev Burn a specific amount of tokens of other token holders if refund process enable. * @param _from The address of token holder whose tokens to be burned. */ function burnFromAddress(address _from) onlyIco public { uint256 amount = balances[_from]; require(_from != address(0)); require(amount > 0); require(amount <= balances[_from]); balances[_from] = balances[_from].sub(amount); totalSupply_ = totalSupply_.sub(amount); Transfer(_from, address(0), amount); } } // File: contracts/Whitelist.sol /** * @title Whitelist contract * @dev Whitelist for wallets. */ contract Whitelist is Ownable { mapping(address => bool) whitelist; uint256 public whitelistLength = 0; address public backendAddress; /** * @dev Add wallet to whitelist. * @dev Accept request from the owner only. * @param _wallet The address of wallet to add. */ function addWallet(address _wallet) public onlyPrivilegedAddresses { require(_wallet != address(0)); require(!isWhitelisted(_wallet)); whitelist[_wallet] = true; whitelistLength++; } /** * @dev Remove wallet from whitelist. * @dev Accept request from the owner only. * @param _wallet The address of whitelisted wallet to remove. */ function removeWallet(address _wallet) public onlyOwner { require(_wallet != address(0)); require(isWhitelisted(_wallet)); whitelist[_wallet] = false; whitelistLength--; } /** * @dev Check the specified wallet whether it is in the whitelist. * @param _wallet The address of wallet to check. */ function isWhitelisted(address _wallet) constant public returns (bool) { return whitelist[_wallet]; } /** * @dev Sets the backend address for automated operations. * @param _backendAddress The backend address to allow. */ function setBackendAddress(address _backendAddress) public onlyOwner { require(_backendAddress != address(0)); backendAddress = _backendAddress; } /** * @dev Allows the function to be called only by the owner and backend. */ modifier onlyPrivilegedAddresses() { require(msg.sender == owner || msg.sender == backendAddress); _; } } // File: contracts/Whitelistable.sol contract Whitelistable { Whitelist public whitelist; modifier whenWhitelisted(address _wallet) { require(whitelist.isWhitelisted(_wallet)); _; } /** * @dev Constructor for Whitelistable contract. */ function Whitelistable() public { whitelist = new Whitelist(); } } // File: contracts/TiqpitCrowdsale.sol contract TiqpitCrowdsale is Pausable, Whitelistable { using SafeMath for uint256; uint256 constant private DECIMALS = 18; uint256 constant public RESERVED_TOKENS_BOUNTY = 10e6 * (10 ** DECIMALS); uint256 constant public RESERVED_TOKENS_FOUNDERS = 25e6 * (10 ** DECIMALS); uint256 constant public RESERVED_TOKENS_ADVISORS = 25e5 * (10 ** DECIMALS); uint256 constant public RESERVED_TOKENS_TIQPIT_SOLUTIONS = 625e5 * (10 ** DECIMALS); uint256 constant public MIN_INVESTMENT = 200 * (10 ** DECIMALS); uint256 constant public MINCAP_TOKENS_PRE_ICO = 1e6 * (10 ** DECIMALS); uint256 constant public MAXCAP_TOKENS_PRE_ICO = 75e5 * (10 ** DECIMALS); uint256 constant public MINCAP_TOKENS_ICO = 5e6 * (10 ** DECIMALS); uint256 constant public MAXCAP_TOKENS_ICO = 3925e5 * (10 ** DECIMALS); uint256 public tokensRemainingIco = MAXCAP_TOKENS_ICO; uint256 public tokensRemainingPreIco = MAXCAP_TOKENS_PRE_ICO; uint256 public soldTokensPreIco = 0; uint256 public soldTokensIco = 0; uint256 public soldTokensTotal = 0; uint256 public preIcoRate = 2857; // 1 PIT = 0.00035 ETH //Base rate for Pre-ICO stage. // ICO rates uint256 public firstRate = 2500; // 1 PIT = 0.0004 ETH uint256 public secondRate = 2222; // 1 PIT = 0.00045 ETH uint256 public thirdRate = 2000; // 1 PIT = 0.0005 ETH uint256 public startTimePreIco = 0; uint256 public endTimePreIco = 0; uint256 public startTimeIco = 0; uint256 public endTimeIco = 0; uint256 public weiRaisedPreIco = 0; uint256 public weiRaisedIco = 0; uint256 public weiRaisedTotal = 0; TiqpitToken public token = new TiqpitToken(this); // Key - address of wallet, Value - address of contract. mapping (address => address) private lockedList; address private tiqpitSolutionsWallet; address private foundersWallet; address private advisorsWallet; address private bountyWallet; address public backendAddress; bool private hasPreIcoFailed = false; bool private hasIcoFailed = false; bool private isInitialDistributionDone = false; struct Purchase { uint256 refundableWei; uint256 burnableTiqs; } mapping(address => Purchase) private preIcoPurchases; mapping(address => Purchase) private icoPurchases; /** * @dev Constructor for TiqpitCrowdsale contract. * @dev Set the owner who can manage whitelist and token. * @param _startTimePreIco The pre-ICO start time. * @param _endTimePreIco The pre-ICO end time. * @param _foundersWallet The address to which reserved tokens for founders will be transferred. * @param _advisorsWallet The address to which reserved tokens for advisors. * @param _tiqpitSolutionsWallet The address to which reserved tokens for Tiqpit Solutions. */ function TiqpitCrowdsale( uint256 _startTimePreIco, uint256 _endTimePreIco, uint256 _startTimeIco, uint256 _endTimeIco, address _foundersWallet, address _advisorsWallet, address _tiqpitSolutionsWallet, address _bountyWallet ) Whitelistable() public { require(_bountyWallet != address(0) && _foundersWallet != address(0) && _tiqpitSolutionsWallet != address(0) && _advisorsWallet != address(0)); require(_startTimePreIco >= now && _endTimePreIco > _startTimePreIco); require(_startTimeIco >= _endTimePreIco && _endTimeIco > _startTimeIco); startTimePreIco = _startTimePreIco; endTimePreIco = _endTimePreIco; startTimeIco = _startTimeIco; endTimeIco = _endTimeIco; tiqpitSolutionsWallet = _tiqpitSolutionsWallet; advisorsWallet = _advisorsWallet; foundersWallet = _foundersWallet; bountyWallet = _bountyWallet; whitelist.transferOwnership(msg.sender); token.transferOwnership(msg.sender); } /** * @dev Fallback function can be used to buy tokens. */ function() public payable { sellTokens(); } /** * @dev Check whether the pre-ICO is active at the moment. */ function isPreIco() public view returns (bool) { return now >= startTimePreIco && now <= endTimePreIco; } /** * @dev Check whether the ICO is active at the moment. */ function isIco() public view returns (bool) { return now >= startTimeIco && now <= endTimeIco; } /** * @dev Burn Remaining Tokens. */ function burnRemainingTokens() onlyOwner public { require(tokensRemainingIco > 0); require(now > endTimeIco); token.burnFromAddress(this); tokensRemainingIco = 0; } /** * @dev Send tokens to Advisors & Tiqpit Solutions Wallets. * @dev Locked tokens for Founders wallet. */ function initialDistribution() onlyOwner public { require(!isInitialDistributionDone); token.transferFromIco(bountyWallet, RESERVED_TOKENS_BOUNTY); token.transferFromIco(advisorsWallet, RESERVED_TOKENS_ADVISORS); token.transferFromIco(tiqpitSolutionsWallet, RESERVED_TOKENS_TIQPIT_SOLUTIONS); lockTokens(foundersWallet, RESERVED_TOKENS_FOUNDERS, 1 years); isInitialDistributionDone = true; } /** * @dev Get Purchase by investor's address. * @param _address The address of a ICO investor. */ function getIcoPurchase(address _address) view public returns(uint256 weis, uint256 tokens) { return (icoPurchases[_address].refundableWei, icoPurchases[_address].burnableTiqs); } /** * @dev Get Purchase by investor's address. * @param _address The address of a Pre-ICO investor. */ function getPreIcoPurchase(address _address) view public returns(uint256 weis, uint256 tokens) { return (preIcoPurchases[_address].refundableWei, preIcoPurchases[_address].burnableTiqs); } /** * @dev Refund Ether invested in pre-ICO to the sender if pre-ICO failed. */ function refundPreIco() public { require(hasPreIcoFailed); require(preIcoPurchases[msg.sender].burnableTiqs > 0 && preIcoPurchases[msg.sender].refundableWei > 0); uint256 amountWei = preIcoPurchases[msg.sender].refundableWei; msg.sender.transfer(amountWei); preIcoPurchases[msg.sender].refundableWei = 0; preIcoPurchases[msg.sender].burnableTiqs = 0; token.burnFromAddress(msg.sender); } /** * @dev Refund Ether invested in ICO to the sender if ICO failed. */ function refundIco() public { require(hasIcoFailed); require(icoPurchases[msg.sender].burnableTiqs > 0 && icoPurchases[msg.sender].refundableWei > 0); uint256 amountWei = icoPurchases[msg.sender].refundableWei; msg.sender.transfer(amountWei); icoPurchases[msg.sender].refundableWei = 0; icoPurchases[msg.sender].burnableTiqs = 0; token.burnFromAddress(msg.sender); } /** * @dev Manual burn tokens from specified address. * @param _address The address of a investor. */ function burnTokens(address _address) onlyOwner public { require(hasIcoFailed); require(icoPurchases[_address].burnableTiqs > 0 || preIcoPurchases[_address].burnableTiqs > 0); icoPurchases[_address].burnableTiqs = 0; preIcoPurchases[_address].burnableTiqs = 0; token.burnFromAddress(_address); } /** * @dev Manual send tokens for specified address. * @param _address The address of a investor. * @param _tokensAmount Amount of tokens. */ function manualSendTokens(address _address, uint256 _tokensAmount) whenWhitelisted(_address) public onlyPrivilegedAddresses { require(_tokensAmount > 0); if (isPreIco() && _tokensAmount <= tokensRemainingPreIco) { token.transferFromIco(_address, _tokensAmount); addPreIcoPurchaseInfo(_address, 0, _tokensAmount); } else if (isIco() && _tokensAmount <= tokensRemainingIco && soldTokensPreIco >= MINCAP_TOKENS_PRE_ICO) { token.transferFromIco(_address, _tokensAmount); addIcoPurchaseInfo(_address, 0, _tokensAmount); } else { revert(); } } /** * @dev Get Locked Contract Address. */ function getLockedContractAddress(address wallet) public view returns(address) { return lockedList[wallet]; } /** * @dev Enable refund process. */ function triggerFailFlags() onlyOwner public { if (!hasPreIcoFailed && now > endTimePreIco && soldTokensPreIco < MINCAP_TOKENS_PRE_ICO) { hasPreIcoFailed = true; } if (!hasIcoFailed && now > endTimeIco && soldTokensIco < MINCAP_TOKENS_ICO) { hasIcoFailed = true; } } /** * @dev Calculate rate for ICO phase. */ function currentIcoRate() public view returns(uint256) { if (now > startTimeIco && now <= startTimeIco + 5 days) { return firstRate; } if (now > startTimeIco + 5 days && now <= startTimeIco + 10 days) { return secondRate; } if (now > startTimeIco + 10 days) { return thirdRate; } } /** * @dev Sell tokens during Pre-ICO && ICO stages. * @dev Sell tokens only for whitelisted wallets. */ function sellTokens() whenWhitelisted(msg.sender) whenNotPaused public payable { require(msg.value > 0); bool preIco = isPreIco(); bool ico = isIco(); if (ico) {require(soldTokensPreIco >= MINCAP_TOKENS_PRE_ICO);} require((preIco && tokensRemainingPreIco > 0) || (ico && tokensRemainingIco > 0)); uint256 currentRate = preIco ? preIcoRate : currentIcoRate(); uint256 weiAmount = msg.value; uint256 tokensAmount = weiAmount.mul(currentRate); require(tokensAmount >= MIN_INVESTMENT); if (ico) { // Move unsold Pre-Ico tokens for current phase. if (tokensRemainingPreIco > 0) { tokensRemainingIco = tokensRemainingIco.add(tokensRemainingPreIco); tokensRemainingPreIco = 0; } } uint256 tokensRemaining = preIco ? tokensRemainingPreIco : tokensRemainingIco; if (tokensAmount > tokensRemaining) { uint256 tokensRemainder = tokensAmount.sub(tokensRemaining); tokensAmount = tokensAmount.sub(tokensRemainder); uint256 overpaidWei = tokensRemainder.div(currentRate); msg.sender.transfer(overpaidWei); weiAmount = msg.value.sub(overpaidWei); } token.transferFromIco(msg.sender, tokensAmount); if (preIco) { addPreIcoPurchaseInfo(msg.sender, weiAmount, tokensAmount); if (soldTokensPreIco >= MINCAP_TOKENS_PRE_ICO) { tiqpitSolutionsWallet.transfer(this.balance); } } if (ico) { addIcoPurchaseInfo(msg.sender, weiAmount, tokensAmount); if (soldTokensIco >= MINCAP_TOKENS_ICO) { tiqpitSolutionsWallet.transfer(this.balance); } } } /** * @dev Add new investment to the Pre-ICO investments storage. * @param _address The address of a Pre-ICO investor. * @param _amountWei The investment received from a Pre-ICO investor. * @param _amountTokens The tokens that will be sent to Pre-ICO investor. */ function addPreIcoPurchaseInfo(address _address, uint256 _amountWei, uint256 _amountTokens) internal { preIcoPurchases[_address].refundableWei = preIcoPurchases[_address].refundableWei.add(_amountWei); preIcoPurchases[_address].burnableTiqs = preIcoPurchases[_address].burnableTiqs.add(_amountTokens); soldTokensPreIco = soldTokensPreIco.add(_amountTokens); tokensRemainingPreIco = tokensRemainingPreIco.sub(_amountTokens); weiRaisedPreIco = weiRaisedPreIco.add(_amountWei); soldTokensTotal = soldTokensTotal.add(_amountTokens); weiRaisedTotal = weiRaisedTotal.add(_amountWei); } /** * @dev Add new investment to the ICO investments storage. * @param _address The address of a ICO investor. * @param _amountWei The investment received from a ICO investor. * @param _amountTokens The tokens that will be sent to ICO investor. */ function addIcoPurchaseInfo(address _address, uint256 _amountWei, uint256 _amountTokens) internal { icoPurchases[_address].refundableWei = icoPurchases[_address].refundableWei.add(_amountWei); icoPurchases[_address].burnableTiqs = icoPurchases[_address].burnableTiqs.add(_amountTokens); soldTokensIco = soldTokensIco.add(_amountTokens); tokensRemainingIco = tokensRemainingIco.sub(_amountTokens); weiRaisedIco = weiRaisedIco.add(_amountWei); soldTokensTotal = soldTokensTotal.add(_amountTokens); weiRaisedTotal = weiRaisedTotal.add(_amountWei); } /** * @dev Locked specified amount of tokens for specified wallet. * @param _wallet The address of wallet. * @param _amount The tokens for locked. * @param _time The time for locked period. */ function lockTokens(address _wallet, uint256 _amount, uint256 _time) internal { LockedOutTokens locked = new LockedOutTokens(_wallet, token, endTimePreIco, 1, _amount, _time); lockedList[_wallet] = locked; token.transferFromIco(locked, _amount); } /** * @dev Sets the backend address for automated operations. * @param _backendAddress The backend address to allow. */ function setBackendAddress(address _backendAddress) public onlyOwner { require(_backendAddress != address(0)); backendAddress = _backendAddress; } /** * @dev Allows the function to be called only by the owner and backend. */ modifier onlyPrivilegedAddresses() { require(msg.sender == owner || msg.sender == backendAddress); _; } }
TOD1
pragma solidity ^0.4.18; /** Mockup object */ contract ElementhToken { bool public mintingFinished = false; function mint(address _to, uint256 _amount) public returns (bool) { if(_to != address(0)) mintingFinished = false; if(_amount != 0) mintingFinished = false; return true; } function burn(address _to, uint256 _amount) public returns (bool) { if(_to != address(0)) mintingFinished = false; if(_amount != 0) mintingFinished = false; return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { mapping(address => bool) internal owners; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public{ owners[msg.sender] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owners[msg.sender] == true); _; } function addOwner(address newAllowed) onlyOwner public { owners[newAllowed] = true; } function removeOwner(address toRemove) onlyOwner public { owners[toRemove] = false; } function isOwner() public view returns(bool){ return owners[msg.sender] == true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. The contract requires a MintableToken that will be * minted as contributions arrive, note that the crowdsale contract * must be owner of the token in order to be able to mint it. */ contract PreFund is Ownable { using SafeMath for uint256; mapping (address => uint256) public deposited; mapping (address => uint256) public claimed; // The token being sold ElementhToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; bool public refundEnabled; event Refunded(address indexed beneficiary, uint256 weiAmount); event AddDeposit(address indexed beneficiary, uint256 value); event LogClaim(address indexed holder, uint256 amount); function setStartTime(uint256 _startTime) public onlyOwner{ startTime = _startTime; } function setEndTime(uint256 _endTime) public onlyOwner{ endTime = _endTime; } function setWallet(address _wallet) public onlyOwner{ wallet = _wallet; } function setRate(uint256 _rate) public onlyOwner{ rate = _rate; } function setRefundEnabled(bool _refundEnabled) public onlyOwner{ refundEnabled = _refundEnabled; } function PreFund(uint256 _startTime, uint256 _endTime, address _wallet, ElementhToken _token) public { require(_startTime >= now); require(_endTime >= _startTime); require(_wallet != address(0)); require(_token != address(0)); token = _token; startTime = _startTime; endTime = _endTime; wallet = _wallet; refundEnabled = false; } function () external payable { deposit(msg.sender); } function addFunds() public payable onlyOwner {} // low level token purchase function function deposit(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); deposited[beneficiary] = deposited[beneficiary].add(msg.value); uint256 weiAmount = msg.value; AddDeposit(beneficiary, weiAmount); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // send ether to the fund collection wallet function forwardFunds() onlyOwner public { require(now >= endTime); wallet.transfer(this.balance); } function claimToken() public { require (msg.sender != address(0)); require (now >= endTime); require (deposited[msg.sender] > 0); require (claimed[msg.sender] == 0); uint tokens = deposited[msg.sender] * rate; token.mint(msg.sender, tokens); claimed[msg.sender] = tokens; LogClaim(msg.sender, tokens); } function refundWallet(address _wallet) onlyOwner public { refundFunds(_wallet); } function claimRefund() public { refundFunds(msg.sender); } function refundFunds(address _wallet) internal { require(_wallet != address(0)); require(deposited[_wallet] > 0); if(claimed[msg.sender] > 0){ require(now > endTime); require(refundEnabled); token.burn(_wallet, claimed[_wallet]); claimed[_wallet] = 0; } else { require(now < endTime); } uint256 depositedValue = deposited[_wallet]; deposited[_wallet] = 0; _wallet.transfer(depositedValue); Refunded(_wallet, depositedValue); } }
TOD1
pragma solidity ^0.4.18; // solhint-disable-line /* SHOW ME WHAT YOU GOT ___ . -^ `--, /# =========`-_ /# (--====___====\ /# .- --. . --.| /## | * ) ( * ), |## \ /\ \ / | |### --- \ --- | |#### ___) #| |###### ##| \##### ---------- / \#### ( `\### | \### | \## | \###. .) `======/ */ // similar to the original shrimper , with these changes: // 0. already initialized // 1. the "free" 314 Morties cost 0.001 eth (in line with the mining fee) // 2. bots should have a harder time, and whales can compete for the devfee contract RickAndMortyShrimper{ string public name = "RickAndMortyShrimper"; string public symbol = "RickAndMortyS"; //uint256 morties_PER_RickAndMorty_PER_SECOND=1; uint256 public morties_TO_HATCH_1RickAndMorty=86400;//for final version should be seconds in a day uint256 public STARTING_RickAndMorty=314; uint256 PSN=10000; uint256 PSNH=5000; bool public initialized=true; address public ceoAddress; mapping (address => uint256) public hatcheryRickAndMorty; mapping (address => uint256) public claimedmorties; mapping (address => uint256) public lastHatch; mapping (address => address) public referrals; uint256 public marketmorties = 1000000000; uint256 public RnMmasterReq=100000; function RickAndMortyShrimper() public{ ceoAddress=msg.sender; } modifier onlyCEO(){ require(msg.sender == ceoAddress ); _; } function becomePickleRick() public{ require(initialized); require(hatcheryRickAndMorty[msg.sender]>=RnMmasterReq); hatcheryRickAndMorty[msg.sender]=SafeMath.sub(hatcheryRickAndMorty[msg.sender],RnMmasterReq); RnMmasterReq=SafeMath.add(RnMmasterReq,100000);//+100k RickAndMortys each time ceoAddress=msg.sender; } function hatchMorties(address ref) public{ require(initialized); if(referrals[msg.sender]==0 && referrals[msg.sender]!=msg.sender){ referrals[msg.sender]=ref; } uint256 mortiesUsed=getMymorties(); uint256 newRickAndMorty=SafeMath.div(mortiesUsed,morties_TO_HATCH_1RickAndMorty); hatcheryRickAndMorty[msg.sender]=SafeMath.add(hatcheryRickAndMorty[msg.sender],newRickAndMorty); claimedmorties[msg.sender]=0; lastHatch[msg.sender]=now; //send referral morties claimedmorties[referrals[msg.sender]]=SafeMath.add(claimedmorties[referrals[msg.sender]],SafeMath.div(mortiesUsed,5)); //boost market to nerf RickAndMorty hoarding marketmorties=SafeMath.add(marketmorties,SafeMath.div(mortiesUsed,10)); } function sellMorties() public{ require(initialized); uint256 hasmorties=getMymorties(); uint256 eggValue=calculatemortiesell(hasmorties); uint256 fee=devFee(eggValue); claimedmorties[msg.sender]=0; lastHatch[msg.sender]=now; marketmorties=SafeMath.add(marketmorties,hasmorties); ceoAddress.transfer(fee); } function buyMorties() public payable{ require(initialized); uint256 mortiesBought=calculateEggBuy(msg.value,SafeMath.sub(this.balance,msg.value)); mortiesBought=SafeMath.sub(mortiesBought,devFee(mortiesBought)); ceoAddress.transfer(devFee(msg.value)); claimedmorties[msg.sender]=SafeMath.add(claimedmorties[msg.sender],mortiesBought); } //magic trade balancing algorithm function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){ //(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt)); return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt))); } function calculatemortiesell(uint256 morties) public view returns(uint256){ return calculateTrade(morties,marketmorties,this.balance); } function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){ return calculateTrade(eth,contractBalance,marketmorties); } function calculateEggBuySimple(uint256 eth) public view returns(uint256){ return calculateEggBuy(eth,this.balance); } function devFee(uint256 amount) public view returns(uint256){ return SafeMath.div(SafeMath.mul(amount,4),100); } function seedMarket(uint256 morties) public payable{ require(marketmorties==0); initialized=true; marketmorties=morties; } function getFreeRickAndMorty() public payable{ require(initialized); require(msg.value==0.001 ether); //similar to mining fee, prevents bots ceoAddress.transfer(msg.value); //RnMmaster gets this entrance fee require(hatcheryRickAndMorty[msg.sender]==0); lastHatch[msg.sender]=now; hatcheryRickAndMorty[msg.sender]=STARTING_RickAndMorty; } function getBalance() public view returns(uint256){ return this.balance; } function getMyRickAndMorty() public view returns(uint256){ return hatcheryRickAndMorty[msg.sender]; } function getRnMmasterReq() public view returns(uint256){ return RnMmasterReq; } function getMymorties() public view returns(uint256){ return SafeMath.add(claimedmorties[msg.sender],getmortiesSinceLastHatch(msg.sender)); } function getmortiesSinceLastHatch(address adr) public view returns(uint256){ uint256 secondsPassed=min(morties_TO_HATCH_1RickAndMorty,SafeMath.sub(now,lastHatch[adr])); return SafeMath.mul(secondsPassed,hatcheryRickAndMorty[adr]); } function min(uint256 a, uint256 b) private pure returns (uint256) { return a < b ? a : b; } function transferOwnership() onlyCEO public { uint256 etherBalance = this.balance; ceoAddress.transfer(etherBalance); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
TOD1
pragma solidity ^0.4.15; contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { bool public stopped; modifier stopInEmergency { require(!stopped); _; } modifier onlyInEmergency { require(stopped); _; } // called by the owner on emergency, triggers stopped state function emergencyStop() external onlyOwner { stopped = true; } // called by the owner on end of emergency, returns to normal state function release() external onlyOwner onlyInEmergency { stopped = false; } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayments() { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } } contract Crowdsale is Pausable, PullPayment { using SafeMath for uint; struct Backer { uint weiReceived; // Amount of Ether given uint256 coinSent; } /* * Constants */ /* Minimum number of DARFtoken to sell */ uint public constant MIN_CAP = 100000 ether; // 100,000 DARFtokens /* Maximum number of DARFtoken to sell */ uint public constant MAX_CAP = 8000000 ether; // 8,000,000 DARFtokens /* Minimum amount to BUY */ uint public constant MIN_BUY_ETHER = 100 finney; /* If backer buy over 1 000 000 DARF (2000 Ether) he/she can clame to become an investor after signing additional agreement with KYC procedure and get 1% of project profit per every 1 000 000 DARF */ struct Potential_Investor { uint weiReceived; // Amount of Ether given uint256 coinSent; uint profitshare; // Amount of Ether given } uint public constant MIN_INVEST_BUY = 2000 ether; /* But only 49% of profit can be distributed this way for bakers who will be first */ uint public MAX_INVEST_SHARE = 4900; // 4900 from 10000 is 49%, becouse Soliditi stil don't support fixed /* Crowdsale period */ uint private constant CROWDSALE_PERIOD = 62 days; /* Number of DARFtokens per Ether */ uint public constant COIN_PER_ETHER = 500; // 500 DARF per ether uint public constant BIGSELL = COIN_PER_ETHER * 100 ether; // when 1 buy is over 50000 DARF (or 100 ether), in means additional bonus 30% /* * Variables */ /* DARFtoken contract reference */ DARFtoken public coin; /* Multisig contract that will receive the Ether */ address public multisigEther; /* Number of Ether received */ uint public etherReceived; /* Number of DARFtokens sent to Ether contributors */ uint public coinSentToEther; /* Number of DARFtokens sent to potential investors */ uint public invcoinSentToEther; /* Crowdsale start time */ uint public startTime; /* Crowdsale end time */ uint public endTime; /* Is crowdsale still on going */ bool public crowdsaleClosed; /* Backers Ether indexed by their Ethereum address */ mapping(address => Backer) public backers; mapping(address => Potential_Investor) public Potential_Investors; // list of potential investors /* * Modifiers */ modifier minCapNotReached() { require(!((now < endTime) || coinSentToEther >= MIN_CAP )); _; } modifier respectTimeFrame() { require(!((now < startTime) || (now > endTime ))); _; } /* * Event */ event LogReceivedETH(address addr, uint value); event LogCoinsEmited(address indexed from, uint amount); event LogInvestshare(address indexed from, uint share); /* * Constructor */ function Crowdsale(address _DARFtokenAddress, address _to) { coin = DARFtoken(_DARFtokenAddress); multisigEther = _to; } /* * The fallback function corresponds to a donation in ETH */ function() stopInEmergency respectTimeFrame payable { receiveETH(msg.sender); } /* * To call to start the crowdsale */ function start() onlyOwner { require (startTime == 0); startTime = now ; endTime = now + CROWDSALE_PERIOD; } /* * Receives a donation in Ether */ function receiveETH(address beneficiary) internal { require(!(msg.value < MIN_BUY_ETHER)); // Don't accept funding under a predefined threshold if (multisigEther == beneficiary) return ; // Don't pay tokens if team refund ethers uint coinToSend = bonus(msg.value.mul(COIN_PER_ETHER));// Compute the number of DARFtoken to send require(!(coinToSend.add(coinSentToEther) > MAX_CAP)); Backer backer = backers[beneficiary]; coin.transfer(beneficiary, coinToSend); // Transfer DARFtokens right now backer.coinSent = backer.coinSent.add(coinToSend); backer.weiReceived = backer.weiReceived.add(msg.value); // Update the total wei collected during the crowdfunding for this backer multisigEther.send(msg.value); if (backer.weiReceived > MIN_INVEST_BUY) { // calculate profit share uint share = msg.value.mul(10000).div(MIN_INVEST_BUY); // 100 = 1% from 10000 // compare to all profit share will LT 49% LogInvestshare(msg.sender,share); if (MAX_INVEST_SHARE > share) { Potential_Investor potential_investor = Potential_Investors[beneficiary]; potential_investor.coinSent = backer.coinSent; potential_investor.weiReceived = backer.weiReceived; // Update the total wei collected during the crowdfunding for this potential investor // add share to potential_investor if (potential_investor.profitshare == 0 ) { uint startshare = potential_investor.weiReceived.mul(10000).div(MIN_INVEST_BUY); MAX_INVEST_SHARE = MAX_INVEST_SHARE.sub(startshare); potential_investor.profitshare = potential_investor.profitshare.add(startshare); } else { MAX_INVEST_SHARE = MAX_INVEST_SHARE.sub(share); potential_investor.profitshare = potential_investor.profitshare.add(share); LogInvestshare(msg.sender,potential_investor.profitshare); } } } etherReceived = etherReceived.add(msg.value); // Update the total wei collected during the crowdfunding coinSentToEther = coinSentToEther.add(coinToSend); // Send events LogCoinsEmited(msg.sender ,coinToSend); LogReceivedETH(beneficiary, etherReceived); } /* *Compute the DARFtoken bonus according to the BUYment period */ function bonus(uint256 amount) internal constant returns (uint256) { /* 25%in the first 15 days 20% 16 days 18 days 15% 19 days 21 days 10% 22 days 24 days 5% from 25 days to 27 days 0% from 28 days to 42 days */ if (amount >= BIGSELL ) { amount = amount.add(amount.div(10).mul(3)); }// bonus 30% to buying over 50000 DARF if (now < startTime.add(16 days)) return amount.add(amount.div(4)); // bonus 25% if (now < startTime.add(18 days)) return amount.add(amount.div(5)); // bonus 20% if (now < startTime.add(22 days)) return amount.add(amount.div(20).mul(3)); // bonus 15% if (now < startTime.add(25 days)) return amount.add(amount.div(10)); // bonus 10% if (now < startTime.add(28 days)) return amount.add(amount.div(20)); // bonus 5 return amount; } /* * Finalize the crowdsale, should be called after the refund period */ function finalize() onlyOwner public { if (now < endTime) { // Cannot finalise before CROWDSALE_PERIOD or before selling all coins require (coinSentToEther == MAX_CAP); } require(!(coinSentToEther < MIN_CAP && now < endTime + 15 days)); // If MIN_CAP is not reached donors have 15days to get refund before we can finalise require(multisigEther.send(this.balance)); // Move the remaining Ether to the multisig address uint remains = coin.balanceOf(this); // No burn all of my precisiossss! // if (remains > 0) { // Burn the rest of DARFtokens // require(coin.burn(remains)) ; //} crowdsaleClosed = true; } /* * Failsafe drain */ function drain() onlyOwner { require(owner.send(this.balance)) ; } /** * Allow to change the team multisig address in the case of emergency. */ function setMultisig(address addr) onlyOwner public { require(addr != address(0)) ; multisigEther = addr; } /** * Manually back DARFtoken owner address. */ function backDARFtokenOwner() onlyOwner public { coin.transferOwnership(owner); } /** * Transfer remains to owner in case if impossible to do min BUY */ function getRemainCoins() onlyOwner public { var remains = MAX_CAP - coinSentToEther; uint minCoinsToSell = bonus(MIN_BUY_ETHER.mul(COIN_PER_ETHER) / (1 ether)); require(!(remains > minCoinsToSell)); Backer backer = backers[owner]; coin.transfer(owner, remains); // Transfer DARFtokens right now backer.coinSent = backer.coinSent.add(remains); coinSentToEther = coinSentToEther.add(remains); // Send events LogCoinsEmited(this ,remains); LogReceivedETH(owner, etherReceived); } /* * When MIN_CAP is not reach: * 1) backer call the "approve" function of the DARFtoken token contract with the amount of all DARFtokens they got in order to be refund * 2) backer call the "refund" function of the Crowdsale contract with the same amount of DARFtokens * 3) backer call the "withdrawPayments" function of the Crowdsale contract to get a refund in ETH */ function refund(uint _value) minCapNotReached public { require (_value == backers[msg.sender].coinSent) ; // compare value from backer balance coin.transferFrom(msg.sender, address(this), _value); // get the token back to the crowdsale contract // No burn all of my precisiossss! //require (coin.burn(_value)); // token sent for refund are burnt uint ETHToSend = backers[msg.sender].weiReceived; backers[msg.sender].weiReceived=0; if (ETHToSend > 0) { asyncSend(msg.sender, ETHToSend); // pull payment to get refund in ETH } } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract DARFtoken is StandardToken, Ownable { string public constant name = "DARFtoken"; string public constant symbol = "DAR"; uint public constant decimals = 18; // Constructor function DARFtoken() { totalSupply = 84000000 ether; // to make right number 84 000 000 balances[msg.sender] = totalSupply; // Send all tokens to owner } /** * Burn away the specified amount of DARFtoken tokens */ function burn(uint _value) onlyOwner returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); return true; } }
TOD1
pragma solidity 0.4.25; /** * @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 add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* contract ownership status*/ contract owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } interface tokenRecipient { function receiveApproval(address _from, uint256 _oshiAmount, address _token, bytes _extraData) external; } contract TokenERC20 { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // @param M Multiplier, uint256 public M = 10**uint256(decimals); uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowed; /** oshi for Adamcoin is like wei for Ether, 1 Adamcoin = M * oshi as 1 Ether = 1e18 wei */ // This generates a public event on the blockchain that will notify clients event Transfer(address indexed _from, address indexed _to, uint256 _oshiAmount); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _approvedBy, address _spender, uint256 _oshiAmount); // This notifies clients about the amount burnt event Burn(address indexed _from, uint256 _oshiAmount); /** * Constructor * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * M; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens 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 _oshiAmount) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_oshiAmount); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_oshiAmount); emit Transfer(_from, _to, _oshiAmount); } /** * Transfer tokens * * Send `_oshiAmount` tokens to `_to` from your account * * @param _to The address of the recipient * @param _oshiAmount the amount of oshi to send */ function transfer(address _to, uint256 _oshiAmount) public { _transfer(msg.sender, _to, _oshiAmount); } /** * Transfer tokens from other address * * Send `_oshiAmount` to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _oshiAmount the amount or oshi to send */ function transferFrom(address _from, address _to, uint256 _oshiAmount) public returns (bool success) { require(_oshiAmount <= balanceOf[_from]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_oshiAmount); require(_oshiAmount > 0 && _from != _to); _transfer(_from, _to, _oshiAmount); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_oshiAmount` tokens in your behalf * * @param _spender The address authorized to spend * @param _oshiAmount the max amount of oshi they can spend */ function approve(address _spender, uint _oshiAmount) public returns (bool success) { allowed[msg.sender][_spender] = _oshiAmount; emit Approval(msg.sender, _spender, _oshiAmount); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_oshiAmount` in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _oshiAmount the max amount of oshi they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _oshiAmount, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _oshiAmount)) { spender.receiveApproval(msg.sender, _oshiAmount, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_oshiAmount` from the system irreversibly * * @param _oshiAmount the amount of oshi to burn */ function burn(uint256 _oshiAmount) public returns (bool success) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(_oshiAmount); // Subtract from the sender totalSupply = totalSupply.sub(_oshiAmount); // Updates totalSupply emit Burn(msg.sender, _oshiAmount); return true; } /** * Destroy tokens from other account * * Remove `_oshiAmount` from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _oshiAmount the amount of oshi to burn */ function burnFrom(address _from, uint256 _oshiAmount) public returns (bool success) { balanceOf[_from] = balanceOf[_from].sub(_oshiAmount); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_oshiAmount); // Subtract from the sender's allowed totalSupply = totalSupply.sub(_oshiAmount); // Update totalSupply emit Burn(_from, _oshiAmount); return true; } } /******************************************/ /* ADAMCOINS ADM STARTS HERE */ /******************************************/ contract Adamcoins is owned, TokenERC20 { using SafeMath for uint256; uint256 public sellPrice; //Adamcoins sell price uint256 public buyPrice; //Adamcoins buy price bool public purchasingAllowed = true; bool public sellingAllowed = true; mapping (address => uint) public pendingWithdrawals; 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( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /// @dev Public function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) view public returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @notice allows to purchase from the contract function enablePurchasing() onlyOwner public { require (msg.sender == owner); purchasingAllowed = true; } /// @notice doesn't allow to purchase from the contract function disablePurchasing() onlyOwner public { require (msg.sender == owner); purchasingAllowed = false; } /// @notice allows to sell to the contract function enableSelling() onlyOwner public { require (msg.sender == owner); sellingAllowed = true; } /// @notice doesn't allow to sell to the contract function disableSelling() onlyOwner public { require (msg.sender == owner); sellingAllowed = false; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _oshiAmount) internal { require (_to != 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(_oshiAmount); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_oshiAmount); // Add the same to the recipient emit Transfer(_from, _to, _oshiAmount); } /// @notice Create `mintedOshiAmount` and send it to `target` /// @param target Address to receive oshi /// @param mintedOshiAmount the amount of oshi it will receive function mintToken(address target, uint256 mintedOshiAmount) onlyOwner public returns (bool) { balanceOf[target] = balanceOf[target].add(mintedOshiAmount); totalSupply = totalSupply.add(mintedOshiAmount); emit Transfer(0, address(this), mintedOshiAmount); emit Transfer(address(this), target, mintedOshiAmount); 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 Allow users to buy adamcoins for `newBuyPrice` and sell adamcoins for `newSellPrice` /// @param newSellPrice the Price in wei that users can sell to the contract /// @param newBuyPrice the Price in wei that users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /* transfer amount of wei to owner*/ function withdrawEther(uint256 amount) onlyOwner public { require(msg.sender == owner); owner.transfer(amount); } /// @notice This method can be used by the owner to extract sent tokens /// or ethers to this contract. /// @param _token The address of token contract that you want to recover /// set to 0 address in case of ether function claimTokens(address _token) onlyOwner public { if (_token == 0x0) { owner.transfer(address(this).balance); return; } TokenERC20 token = TokenERC20(_token); uint balance = token.balanceOf(address(this)); token.transfer(owner, balance); } /// @notice Buy tokens from contract by sending ether function() public payable { require(msg.value > 0); require(purchasingAllowed); uint tokens = (msg.value * M)/buyPrice; // calculates the amount pendingWithdrawals[msg.sender] = pendingWithdrawals[msg.sender].add(tokens); // update the pendingWithdrawals amount for buyer } /// @notice Withdraw the amount of pendingWithdrawals from contract function withdrawAdamcoins() public { require(purchasingAllowed); uint withdrawalAmount = pendingWithdrawals[msg.sender]; // calculates withdrawal amount pendingWithdrawals[msg.sender] = 0; _transfer(address(this), msg.sender, withdrawalAmount); // makes the transfers } /// @notice Sell Adamcoins to the contract /// @param _adamcoinsAmountToSell amount of Adamcoins to be sold function sell(uint256 _adamcoinsAmountToSell) public { require(sellingAllowed); uint256 weiAmount = _adamcoinsAmountToSell.mul(sellPrice); require(address(this).balance >= weiAmount); // checks if the contract has enough ether to buy uint adamcoinsAmountToSell = _adamcoinsAmountToSell * M; _transfer(msg.sender, address(this), adamcoinsAmountToSell); // makes the transfers msg.sender.transfer(weiAmount); // sends ether to the seller. } }
TOD1
pragma solidity ^0.4.20; contract think_and_get_rich { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function set_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.25; contract QUICK_QUIZ { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; bytes32 questionerPin = 0x2f66052a85afaa57dac96fdadae2bbb794178f8448687866370a40a7af19c390; function Activate(bytes32 _questionerPin, string _question, string _response) public payable { if(keccak256(_questionerPin)==questionerPin) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; questionerPin = 0x0; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC20 { function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool); function mintFromICO(address _to, uint256 _amount) external returns(bool); } contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract MainSale is Ownable { ERC20 public token; using SafeMath for uint; address public backEndOperator = msg.sender; address team = 0x7DDA135cDAa44Ad3D7D79AAbE562c4cEA9DEB41d; // 25% all address reserve = 0x34bef601666D7b2E719Ff919A04266dD07706a79; // 15% all mapping(address=>bool) public whitelist; mapping(address => uint256) public investedEther; uint256 public startSale = 1537228801; // Tuesday, 18-Sep-18 00:00:01 UTC uint256 public endSale = 1545177599; // Tuesday, 18-Dec-18 23:59:59 UTC uint256 public investors; uint256 public weisRaised; uint256 public dollarRaised; // collected USD uint256 public softCap = 2000000000*1e18; // 20,000,000 USD uint256 public hardCap = 7000000000*1e18; // 70,000,000 USD uint256 public buyPrice; //0.01 USD uint256 public dollarPrice; uint256 public soldTokens; uint256 step1Sum = 3000000*1e18; // 3 mln $ uint256 step2Sum = 10000000*1e18; // 10 mln $ uint256 step3Sum = 20000000*1e18; // 20 mln $ uint256 step4Sum = 30000000*1e18; // 30 mln $ event Authorized(address wlCandidate, uint timestamp); event Revoked(address wlCandidate, uint timestamp); event Refund(uint rate, address investor); modifier isUnderHardCap() { require(weisRaised <= hardCap); _; } modifier backEnd() { require(msg.sender == backEndOperator || msg.sender == owner); _; } constructor(uint256 _dollareth) public { dollarPrice = _dollareth; buyPrice = 1e16/dollarPrice; // 16 decimals because 1 cent hardCap = 7500000000*buyPrice; } function setToken (ERC20 _token) public onlyOwner { token = _token; } function setDollarRate(uint256 _usdether) public onlyOwner { dollarPrice = _usdether; buyPrice = 1e16/dollarPrice; // 16 decimals because 1 cent hardCap = 7500000000*buyPrice; } function setPrice(uint256 newBuyPrice) public onlyOwner { buyPrice = newBuyPrice; } function setStartSale(uint256 newStartSale) public onlyOwner { startSale = newStartSale; } function setEndSale(uint256 newEndSaled) public onlyOwner { endSale = newEndSaled; } function setBackEndAddress(address newBackEndOperator) public onlyOwner { backEndOperator = newBackEndOperator; } /******************************************************************************* * Whitelist's section */ function authorize(address wlCandidate) public backEnd { require(wlCandidate != address(0x0)); require(!isWhitelisted(wlCandidate)); whitelist[wlCandidate] = true; investors++; emit Authorized(wlCandidate, now); } function revoke(address wlCandidate) public onlyOwner { whitelist[wlCandidate] = false; investors--; emit Revoked(wlCandidate, now); } function isWhitelisted(address wlCandidate) public view returns(bool) { return whitelist[wlCandidate]; } /******************************************************************************* * Payable's section */ function isMainSale() public constant returns(bool) { return now >= startSale && now <= endSale; } function () public payable isUnderHardCap { require(isMainSale()); require(isWhitelisted(msg.sender)); require(msg.value >= 10000000000000000); mainSale(msg.sender, msg.value); investedEther[msg.sender] = investedEther[msg.sender].add(msg.value); } function mainSale(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); uint256 tokensSum = tokens.mul(discountSum(msg.value)).div(100); uint256 tokensCollect = tokens.mul(discountCollect()).div(100); tokens = tokens.add(tokensSum).add(tokensCollect); token.mintFromICO(_investor, tokens); uint256 tokensFounders = tokens.mul(5).div(12); token.mintFromICO(team, tokensFounders); uint256 tokensDevelopers = tokens.div(4); token.mintFromICO(reserve, tokensDevelopers); weisRaised = weisRaised.add(msg.value); uint256 valueInUSD = msg.value.mul(dollarPrice); dollarRaised = dollarRaised.add(valueInUSD); soldTokens = soldTokens.add(tokens); } function discountSum(uint256 _tokens) pure private returns(uint256) { if(_tokens >= 10000000*1e18) { // > 100k$ = 10,000,000 TAL return 7; } if(_tokens >= 5000000*1e18) { // 50-100k$ = 5,000,000 TAL return 5; } if(_tokens >= 1000000*1e18) { // 10-50k$ = 1,000,000 TAL return 3; } else return 0; } function discountCollect() view private returns(uint256) { // 20% bonus, if collected sum < 3 mln $ if(dollarRaised <= step1Sum) { return 20; } // 15% bonus, if collected sum < 10 mln $ if(dollarRaised <= step2Sum) { return 15; } // 10% bonus, if collected sum < 20 mln $ if(dollarRaised <= step3Sum) { return 10; } // 5% bonus, if collected sum < 30 mln $ if(dollarRaised <= step4Sum) { return 5; } return 0; } function mintManual(address _investor, uint256 _value) public onlyOwner { token.mintFromICO(_investor, _value); uint256 tokensFounders = _value.mul(5).div(12); token.mintFromICO(team, tokensFounders); uint256 tokensDevelopers = _value.div(4); token.mintFromICO(reserve, tokensDevelopers); } function transferEthFromContract(address _to, uint256 amount) public onlyOwner { require(amount != 0); require(_to != 0x0); _to.transfer(amount); } function refundSale() public { require(soldTokens < softCap && now > endSale); uint256 rate = investedEther[msg.sender]; require(investedEther[msg.sender] >= 0); investedEther[msg.sender] = 0; msg.sender.transfer(rate); weisRaised = weisRaised.sub(rate); emit Refund(rate, msg.sender); } }
TOD1
pragma solidity ^0.4.20; contract CutieCoreInterface { function isCutieCore() pure public returns (bool); function transferFrom(address _from, address _to, uint256 _cutieId) external; function transfer(address _to, uint256 _cutieId) external; function ownerOf(uint256 _cutieId) external view returns (address owner); function getCutie(uint40 _id) external view returns ( uint256 genes, uint40 birthTime, uint40 cooldownEndTime, uint40 momId, uint40 dadId, uint16 cooldownIndex, uint16 generation ); function getGenes(uint40 _id) public view returns ( uint256 genes ); function getCooldownEndTime(uint40 _id) public view returns ( uint40 cooldownEndTime ); function getCooldownIndex(uint40 _id) public view returns ( uint16 cooldownIndex ); function getGeneration(uint40 _id) public view returns ( uint16 generation ); function getOptional(uint40 _id) public view returns ( uint64 optional ); function changeGenes( uint40 _cutieId, uint256 _genes) public; function changeCooldownEndTime( uint40 _cutieId, uint40 _cooldownEndTime) public; function changeCooldownIndex( uint40 _cutieId, uint16 _cooldownIndex) public; function changeOptional( uint40 _cutieId, uint64 _optional) public; function changeGeneration( uint40 _cutieId, uint16 _generation) public; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract MarketInterface { function withdrawEthFromBalance() external; function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable; function bid(uint40 _cutieId) public payable; function cancelActiveAuctionWhenPaused(uint40 _cutieId) public; function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee ); } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract Market is MarketInterface, Pausable { // Shows the auction on an Cutie Token struct Auction { // Price (in wei) at the beginning of auction uint128 startPrice; // Price (in wei) at the end of auction uint128 endPrice; // Current owner of Token address seller; // Auction duration in seconds uint40 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint40 startedAt; // Featuring fee (in wei, optional) uint128 featuringFee; } // Reference to contract that tracks ownership CutieCoreInterface public coreContract; // Cut owner takes on each auction, in basis points - 1/100 of a per cent. // Values 0-10,000 map to 0%-100% uint16 public ownerFee; // Map from token ID to their corresponding auction. mapping (uint40 => Auction) public cutieIdToAuction; event AuctionCreated(uint40 cutieId, uint128 startPrice, uint128 endPrice, uint40 duration, uint128 fee); event AuctionSuccessful(uint40 cutieId, uint128 totalPrice, address winner); event AuctionCancelled(uint40 cutieId); /// @dev disables sending fund to this contract function() external {} modifier canBeStoredIn128Bits(uint256 _value) { require(_value <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); _; } // @dev Adds to the list of open auctions and fires the // AuctionCreated event. // @param _cutieId The token ID is to be put on auction. // @param _auction To add an auction. // @param _fee Amount of money to feature auction function _addAuction(uint40 _cutieId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); cutieIdToAuction[_cutieId] = _auction; emit AuctionCreated( _cutieId, _auction.startPrice, _auction.endPrice, _auction.duration, _auction.featuringFee ); } // @dev Returns true if the token is claimed by the claimant. // @param _claimant - Address claiming to own the token. function _isOwner(address _claimant, uint256 _cutieId) internal view returns (bool) { return (coreContract.ownerOf(_cutieId) == _claimant); } // @dev Transfers the token owned by this contract to another address. // Returns true when the transfer succeeds. // @param _receiver - Address to transfer token to. // @param _cutieId - Token ID to transfer. function _transfer(address _receiver, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transfer(_receiver, _cutieId); } // @dev Escrows the token and assigns ownership to this contract. // Throws if the escrow fails. // @param _owner - Current owner address of token to escrow. // @param _cutieId - Token ID the approval of which is to be verified. function _escrow(address _owner, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transferFrom(_owner, this, _cutieId); } // @dev just cancel auction. function _cancelActiveAuction(uint40 _cutieId, address _seller) internal { _removeAuction(_cutieId); _transfer(_seller, _cutieId); emit AuctionCancelled(_cutieId); } // @dev Calculates the price and transfers winnings. // Does not transfer token ownership. function _bid(uint40 _cutieId, uint128 _bidAmount) internal returns (uint128) { // Get a reference to the auction struct Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); // Check that bid > current price uint128 price = _currentPrice(auction); require(_bidAmount >= price); // Provide a reference to the seller before the auction struct is deleted. address seller = auction.seller; _removeAuction(_cutieId); // Transfer proceeds to seller (if there are any!) if (price > 0) { uint128 fee = _computeFee(price); uint128 sellerValue = price - fee; seller.transfer(sellerValue); } emit AuctionSuccessful(_cutieId, price, msg.sender); return price; } // @dev Removes from the list of open auctions. // @param _cutieId - ID of token on auction. function _removeAuction(uint40 _cutieId) internal { delete cutieIdToAuction[_cutieId]; } // @dev Returns true if the token is on auction. // @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } // @dev calculate current price of auction. // When testing, make this function public and turn on // `Current price calculation` test suite. function _computeCurrentPrice( uint128 _startPrice, uint128 _endPrice, uint40 _duration, uint40 _secondsPassed ) internal pure returns (uint128) { if (_secondsPassed >= _duration) { return _endPrice; } else { int256 totalPriceChange = int256(_endPrice) - int256(_startPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); uint128 currentPrice = _startPrice + uint128(currentPriceChange); return currentPrice; } } // @dev return current price of token. function _currentPrice(Auction storage _auction) internal view returns (uint128) { uint40 secondsPassed = 0; uint40 timeNow = uint40(now); if (timeNow > _auction.startedAt) { secondsPassed = timeNow - _auction.startedAt; } return _computeCurrentPrice( _auction.startPrice, _auction.endPrice, _auction.duration, secondsPassed ); } // @dev Calculates owner's cut of a sale. // @param _price - Sale price of cutie. function _computeFee(uint128 _price) internal view returns (uint128) { return _price * ownerFee / 10000; } // @dev Remove all Ether from the contract with the owner's cuts. Also, remove any Ether sent directly to the contract address. // Transfers to the token contract, but can be called by // the owner or the token contract. function withdrawEthFromBalance() external { address coreAddress = address(coreContract); require( msg.sender == owner || msg.sender == coreAddress ); coreAddress.transfer(address(this).balance); } // @dev create and begin new auction. function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public whenNotPaused payable { require(_isOwner(msg.sender, _cutieId)); _escrow(msg.sender, _cutieId); Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now), uint128(msg.value) ); _addAuction(_cutieId, auction); } // @dev Set the reference to cutie ownership contract. Verify the owner's fee. // @param fee should be between 0-10,000. function setup(address _coreContractAddress, uint16 _fee) public onlyOwner { require(_fee <= 10000); ownerFee = _fee; CutieCoreInterface candidateContract = CutieCoreInterface(_coreContractAddress); require(candidateContract.isCutieCore()); coreContract = candidateContract; } // @dev Set the owner's fee. // @param fee should be between 0-10,000. function setFee(uint16 _fee) public onlyOwner { require(_fee <= 10000); ownerFee = _fee; } // @dev bid on auction. Complete it and transfer ownership of cutie if enough ether was given. function bid(uint40 _cutieId) public payable whenNotPaused canBeStoredIn128Bits(msg.value) { // _bid throws if something failed. _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } // @dev Returns auction info for a token on auction. // @param _cutieId - ID of token on auction. function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt, uint128 featuringFee ) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt, auction.featuringFee ); } // @dev Returns auction info for a token on auction. // @param _cutieId - ID of token on auction. function isOnAuction(uint40 _cutieId) public view returns (bool) { return cutieIdToAuction[_cutieId].startedAt > 0; } /* /// @dev Import cuties from previous version of Core contract. /// @param _oldAddress Old core contract address /// @param _fromIndex (inclusive) /// @param _toIndex (inclusive) function migrate(address _oldAddress, uint40 _fromIndex, uint40 _toIndex) public onlyOwner whenPaused { Market old = Market(_oldAddress); for (uint40 i = _fromIndex; i <= _toIndex; i++) { if (coreContract.ownerOf(i) == _oldAddress) { address seller; uint128 startPrice; uint128 endPrice; uint40 duration; uint40 startedAt; uint128 featuringFee; (seller, startPrice, endPrice, duration, startedAt, featuringFee) = old.getAuctionInfo(i); Auction memory auction = Auction({ seller: seller, startPrice: startPrice, endPrice: endPrice, duration: duration, startedAt: startedAt, featuringFee: featuringFee }); _addAuction(i, auction); } } }*/ // @dev Returns the current price of an auction. function getCurrentPrice(uint40 _cutieId) public view returns (uint128) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return _currentPrice(auction); } // @dev Cancels unfinished auction and returns token to owner. // Can be called when contract is paused. function cancelActiveAuction(uint40 _cutieId) public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelActiveAuction(_cutieId, seller); } // @dev Cancels auction when contract is on pause. Option is available only to owners in urgent situations. Tokens returned to seller. // Used on Core contract upgrade. function cancelActiveAuctionWhenPaused(uint40 _cutieId) whenPaused onlyOwner public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); _cancelActiveAuction(_cutieId, auction.seller); } } /// @title Auction market for cuties sale /// @author https://BlockChainArchitect.io contract SaleMarket is Market { // @dev Sanity check reveals that the // auction in our setSaleAuctionAddress() call is right. bool public isSaleMarket = true; // @dev create and start a new auction // @param _cutieId - ID of cutie to auction, sender must be owner. // @param _startPrice - Price of item (in wei) at the beginning of auction. // @param _endPrice - Price of item (in wei) at the end of auction. // @param _duration - Length of auction (in seconds). // @param _seller - Seller function createAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller ) public payable { require(msg.sender == address(coreContract)); _escrow(_seller, _cutieId); Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now), uint128(msg.value) ); _addAuction(_cutieId, auction); } // @dev LastSalePrice is updated if seller is the token contract. // Otherwise, default bid method is used. function bid(uint40 _cutieId) public payable canBeStoredIn128Bits(msg.value) { // _bid verifies token ID size _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } }
TOD1
pragma solidity 0.4.21; /** * @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 AMBToken { using SafeMath for uint256; string public constant name = "Ambit token"; string public constant symbol = "AMBT"; uint8 public constant decimals = 18; uint256 public totalSupply; bool internal contractIsWorking = true; struct Investor { uint256 tokenBalance; uint256 icoInvest; bool activated; } mapping(address => Investor) internal investors; mapping(address => mapping (address => uint256)) internal allowed; /* Dividend's Structures */ uint256 internal dividendCandidate = 0; uint256[] internal dividends; enum ProfitStatus {Initial, StartFixed, EndFixed, Claimed} struct InvestorProfitData { uint256 start_balance; uint256 end_balance; ProfitStatus status; } mapping(address => mapping(uint32 => InvestorProfitData)) internal profits; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function balanceOf(address _owner) public view returns (uint256 balance) { return investors[_owner].tokenBalance; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function _approve(address _spender, uint256 _value) internal returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { require(investors[msg.sender].activated && contractIsWorking); return _approve(_spender, _value); } function _transfer(address _from, address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= investors[_from].tokenBalance); fixDividendBalances(_to, false); investors[_from].tokenBalance = investors[_from].tokenBalance.sub(_value); investors[_to].tokenBalance = investors[_to].tokenBalance.add(_value); emit Transfer(_from, _to, _value); return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(investors[msg.sender].activated && contractIsWorking); fixDividendBalances(msg.sender, false); return _transfer( msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(investors[msg.sender].activated && investors[_from].activated && contractIsWorking); require(_to != address(0)); require(_value <= investors[_from].tokenBalance); require(_value <= allowed[_from][msg.sender]); fixDividendBalances(_from, false); fixDividendBalances(_to, false); investors[_from].tokenBalance = investors[_from].tokenBalance.sub(_value); investors[_to].tokenBalance = investors[_to].tokenBalance.add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /* Eligible token and balance helper function */ function fixDividendBalances(address investor, bool revertIfClaimed) internal returns (InvestorProfitData storage current_profit, uint256 profit_per_token){ uint32 next_id = uint32(dividends.length); uint32 current_id = next_id - 1; current_profit = profits[investor][current_id]; if (revertIfClaimed) require(current_profit.status != ProfitStatus.Claimed); InvestorProfitData storage next_profit = profits[investor][next_id]; if (current_profit.status == ProfitStatus.Initial) { current_profit.start_balance = investors[investor].tokenBalance; current_profit.end_balance = investors[investor].tokenBalance; current_profit.status = ProfitStatus.EndFixed; next_profit.start_balance = investors[investor].tokenBalance; next_profit.status = ProfitStatus.StartFixed; } else if (current_profit.status == ProfitStatus.StartFixed) { current_profit.end_balance = investors[investor].tokenBalance; current_profit.status = ProfitStatus.EndFixed; next_profit.start_balance = investors[investor].tokenBalance; next_profit.status = ProfitStatus.StartFixed; } profit_per_token = dividends[current_id]; } } contract AMBTICO is AMBToken { uint256 internal constant ONE_TOKEN = 10 ** uint256(decimals);//just for convenience uint256 internal constant MILLION = 1000000; //just for convenience uint256 internal constant BOUNTY_QUANTITY = 3120000; uint256 internal constant RESERV_QUANTITY = 12480000; uint256 internal constant TOKEN_MAX_SUPPLY = 104 * MILLION * ONE_TOKEN; uint256 internal constant BOUNTY_TOKENS = BOUNTY_QUANTITY * ONE_TOKEN; uint256 internal constant RESERV_TOKENS = RESERV_QUANTITY * ONE_TOKEN; uint256 internal constant MIN_SOLD_TOKENS = 200 * ONE_TOKEN; uint256 internal constant SOFTCAP = BOUNTY_TOKENS + RESERV_TOKENS + 6 * MILLION * ONE_TOKEN; uint256 internal constant REFUND_PERIOD = 60 days; uint256 internal constant KYC_REVIEW_PERIOD = 60 days; address internal owner; address internal bountyManager; address internal dividendManager; address internal dApp; enum ContractMode {Initial, TokenSale, UnderSoftCap, DividendDistribution, Destroyed} ContractMode public mode = ContractMode.Initial; uint256 public icoFinishTime = 0; uint256 public tokenSold = 0; uint256 public etherCollected = 0; uint8 public currentSection = 0; uint[4] public saleSectionDiscounts = [ uint8(20), 10, 5]; uint[4] public saleSectionPrice = [ uint256(1000000000000000), 1125000000000000, 1187500000000000, 1250000000000000];//price: 0.40 0.45 0.475 0.50 cent | ETH/USD initial rate: 400 uint[4] public saleSectionCount = [ uint256(17 * MILLION), 20 * MILLION, 20 * MILLION, 47 * MILLION - (BOUNTY_QUANTITY+RESERV_QUANTITY)]; uint[4] public saleSectionInvest = [ uint256(saleSectionCount[0] * saleSectionPrice[0]), saleSectionCount[1] * saleSectionPrice[1], saleSectionCount[2] * saleSectionPrice[2], saleSectionCount[3] * saleSectionPrice[3]]; uint256 public buyBackPriceWei = 0 ether; event OwnershipTransferred (address previousOwner, address newOwner); event BountyManagerAssigned (address previousBountyManager, address newBountyManager); event DividendManagerAssigned (address previousDividendManager, address newDividendManager); event DAppAssigned (address previousDApp, address newDApp); event ModeChanged (ContractMode newMode, uint256 tokenBalance); event DividendDeclared (uint32 indexed dividendID, uint256 profitPerToken); event DividendClaimed (address indexed investor, uint256 amount); event BuyBack (address indexed requestor); event Refund (address indexed investor, uint256 amount); event Handbrake (ContractMode current_mode, bool functioning); event FundsAdded (address owner, uint256 amount); event FundsWithdrawal (address owner, uint256 amount); event BountyTransfered (address recipient, uint256 amount); event PriceChanged (uint256 newPrice); event BurnToken (uint256 amount); modifier grantOwner() { require(msg.sender == owner); _; } modifier grantBountyManager() { require(msg.sender == bountyManager); _; } modifier grantDividendManager() { require(msg.sender == dividendManager); _; } modifier grantDApp() { require(msg.sender == dApp); _; } function AMBTICO() public { owner = msg.sender; dividends.push(0); } function setTokenPrice(uint256 new_wei_price) public grantDApp { require(new_wei_price > 0); uint8 len = uint8(saleSectionPrice.length)-1; for (uint8 i=0; i<=len; i++) { uint256 prdsc = 100 - saleSectionDiscounts[i]; saleSectionPrice[i] = prdsc.mul(new_wei_price ).div(100); saleSectionInvest[i] = saleSectionPrice[i] * saleSectionCount[i]; } emit PriceChanged(new_wei_price); } function startICO() public grantOwner { require(contractIsWorking); require(mode == ContractMode.Initial); require(bountyManager != 0x0); totalSupply = TOKEN_MAX_SUPPLY; investors[this].tokenBalance = TOKEN_MAX_SUPPLY-(BOUNTY_TOKENS+RESERV_TOKENS); investors[bountyManager].tokenBalance = BOUNTY_TOKENS; investors[owner].tokenBalance = RESERV_TOKENS; tokenSold = investors[bountyManager].tokenBalance + investors[owner].tokenBalance; mode = ContractMode.TokenSale; emit ModeChanged(mode, investors[this].tokenBalance); } function getCurrentTokenPrice() public view returns(uint256) { require(currentSection < saleSectionCount.length); return saleSectionPrice[currentSection]; } function () public payable { invest(); } function invest() public payable { _invest(msg.sender,msg.value); } /* Used by ĐApp to accept Bitcoin transfers.*/ function investWithBitcoin(address ethAddress, uint256 ethWEI) public grantDApp { _invest(ethAddress,ethWEI); } function _invest(address msg_sender, uint256 msg_value) internal { require(contractIsWorking); require(currentSection < saleSectionCount.length); require(mode == ContractMode.TokenSale); require(msg_sender != bountyManager); uint wei_value = msg_value; uint _tokens = 0; while (wei_value > 0 && (currentSection < saleSectionCount.length)) { if (saleSectionInvest[currentSection] >= wei_value) { _tokens += ONE_TOKEN.mul(wei_value).div(saleSectionPrice[currentSection]); saleSectionInvest[currentSection] -= wei_value; wei_value =0; } else { _tokens += ONE_TOKEN.mul(saleSectionInvest[currentSection]).div(saleSectionPrice[currentSection]); wei_value -= saleSectionInvest[currentSection]; saleSectionInvest[currentSection] = 0; } if (saleSectionInvest[currentSection] <= 0) currentSection++; } require(_tokens >= MIN_SOLD_TOKENS); require(_transfer(this, msg_sender, _tokens)); profits[msg_sender][1] = InvestorProfitData({ start_balance: investors[msg_sender].tokenBalance, end_balance: investors[msg_sender].tokenBalance, status: ProfitStatus.StartFixed }); investors[msg_sender].icoInvest += (msg_value - wei_value); tokenSold += _tokens; etherCollected += (msg_value - wei_value); if (saleSectionInvest[saleSectionInvest.length-1] == 0 ) { _finishICO(); } if (wei_value > 0) { msg_sender.transfer(wei_value); } } function _finishICO() internal { require(contractIsWorking); require(mode == ContractMode.TokenSale); if (tokenSold >= SOFTCAP) { mode = ContractMode.DividendDistribution; } else { mode = ContractMode.UnderSoftCap; } investors[this].tokenBalance = 0; icoFinishTime = now; totalSupply = tokenSold; emit ModeChanged(mode, investors[this].tokenBalance); } function finishICO() public grantOwner { _finishICO(); } function getInvestedAmount(address investor) public view returns(uint256) { return investors[investor].icoInvest; } function activateAddress(address investor, bool status) public grantDApp { require(contractIsWorking); require(mode == ContractMode.DividendDistribution); require((now - icoFinishTime) < KYC_REVIEW_PERIOD); investors[investor].activated = status; } function isAddressActivated(address investor) public view returns (bool) { return investors[investor].activated; } /******* Dividend Declaration Section *********/ function declareDividend(uint256 profit_per_token) public grantDividendManager { dividendCandidate = profit_per_token; } function confirmDividend(uint256 profit_per_token) public grantOwner { require(contractIsWorking); require(dividendCandidate == profit_per_token); require(mode == ContractMode.DividendDistribution); dividends.push(dividendCandidate); emit DividendDeclared(uint32(dividends.length), dividendCandidate); dividendCandidate = 0; } function claimDividend() public { require(contractIsWorking); require(mode == ContractMode.DividendDistribution); require(investors[msg.sender].activated); InvestorProfitData storage current_profit; uint256 price_per_token; (current_profit, price_per_token) = fixDividendBalances(msg.sender, true); uint256 investorProfitWei = (current_profit.start_balance < current_profit.end_balance ? current_profit.start_balance : current_profit.end_balance ).div(ONE_TOKEN).mul(price_per_token); current_profit.status = ProfitStatus.Claimed; emit DividendClaimed(msg.sender, investorProfitWei); msg.sender.transfer(investorProfitWei); } function getDividendInfo() public view returns(uint256) { return dividends[dividends.length - 1]; } /******* emit BuyBack ********/ function setBuyBackPrice(uint256 token_buyback_price) public grantOwner { require(mode == ContractMode.DividendDistribution); buyBackPriceWei = token_buyback_price; } function buyback() public { require(contractIsWorking); require(mode == ContractMode.DividendDistribution); require(buyBackPriceWei > 0); uint256 token_amount = investors[msg.sender].tokenBalance; uint256 ether_amount = calcTokenToWei(token_amount); require(address(this).balance > ether_amount); if (transfer(this, token_amount)){ emit BuyBack(msg.sender); msg.sender.transfer(ether_amount); } } /******** Under SoftCap Section *********/ function refund() public { require(contractIsWorking); require(mode == ContractMode.UnderSoftCap); require(investors[msg.sender].tokenBalance >0); require(investors[msg.sender].icoInvest>0); require (address(this).balance > investors[msg.sender].icoInvest); if (_transfer(msg.sender, this, investors[msg.sender].tokenBalance)){ emit Refund(msg.sender, investors[msg.sender].icoInvest); msg.sender.transfer(investors[msg.sender].icoInvest); } } function destroyContract() public grantOwner { require(mode == ContractMode.UnderSoftCap); require((now - icoFinishTime) > REFUND_PERIOD); selfdestruct(owner); } /******** Permission related ********/ function transferOwnership(address new_owner) public grantOwner { require(contractIsWorking); require(new_owner != address(0)); emit OwnershipTransferred(owner, new_owner); owner = new_owner; } function setBountyManager(address new_bounty_manager) public grantOwner { require(investors[new_bounty_manager].tokenBalance ==0); if (mode == ContractMode.Initial) { emit BountyManagerAssigned(bountyManager, new_bounty_manager); bountyManager = new_bounty_manager; } else if (mode == ContractMode.TokenSale) { emit BountyManagerAssigned(bountyManager, new_bounty_manager); address old_bounty_manager = bountyManager; bountyManager = new_bounty_manager; require(_transfer(old_bounty_manager, new_bounty_manager, investors[old_bounty_manager].tokenBalance)); } else { revert(); } } function setDividendManager(address new_dividend_manager) public grantOwner { emit DividendManagerAssigned(dividendManager, new_dividend_manager); dividendManager = new_dividend_manager; } function setDApp(address new_dapp) public grantOwner { emit DAppAssigned(dApp, new_dapp); dApp = new_dapp; } /******** Security and funds section ********/ function transferBounty(address _to, uint256 _amount) public grantBountyManager { require(contractIsWorking); require(mode == ContractMode.DividendDistribution); if (_transfer(bountyManager, _to, _amount)) { emit BountyTransfered(_to, _amount); } } function burnTokens(uint256 tokenAmount) public grantOwner { require(contractIsWorking); require(mode == ContractMode.DividendDistribution); require(investors[msg.sender].tokenBalance > tokenAmount); investors[msg.sender].tokenBalance -= tokenAmount; totalSupply = totalSupply.sub(tokenAmount); emit BurnToken(tokenAmount); } function withdrawFunds(uint wei_value) grantOwner external { require(mode != ContractMode.UnderSoftCap); require(address(this).balance >= wei_value); emit FundsWithdrawal(msg.sender, wei_value); msg.sender.transfer(wei_value); } function addFunds() public payable grantOwner { require(contractIsWorking); emit FundsAdded(msg.sender, msg.value); } function pauseContract() public grantOwner { require(contractIsWorking); contractIsWorking = false; emit Handbrake(mode, contractIsWorking); } function restoreContract() public grantOwner { require(!contractIsWorking); contractIsWorking = true; emit Handbrake(mode, contractIsWorking); } /******** Helper functions ********/ function calcTokenToWei(uint256 token_amount) internal view returns (uint256) { return buyBackPriceWei.mul(token_amount).div(ONE_TOKEN); } }
TOD1
pragma solidity ^0.4.24; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } } contract Alchemy { using SafeMath for uint256; // 代币的公共变量:名称、代号、小数点后面的位数、代币发行总量 string public name; string public symbol; uint8 public decimals = 6; // 官方建议18位 uint256 public totalSupply; address public owner; address[] public ownerContracts;// 允许调用的智能合约 address public userPool; address public platformPool; address public smPool; // 代币余额的数据 mapping (address => uint256) public balanceOf; // 代付金额限制 // 比如map[A][B]=60,意思是用户B可以使用A的钱进行消费,使用上限是60,此条数据由A来设置,一般B可以使中间担保平台 mapping (address => mapping (address => uint256)) public allowance; // 交易成功事件,会通知给客户端 event Transfer(address indexed from, address indexed to, uint256 value); // 交易ETH成功事件,会通知给客户端 event TransferETH(address indexed from, address indexed to, uint256 value); // 将销毁的代币量通知给客户端 event Burn(address indexed from, uint256 value); /** * 构造函数 * 初始化代币发行的参数 */ //990000000,"AlchemyChain","ALC" constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) payable public { totalSupply = initialSupply * 10 ** uint256(decimals); // 计算发行量 balanceOf[msg.sender] = totalSupply; // 将发行的币给创建者 name = tokenName; // 设置代币名称 symbol = tokenSymbol; // 设置代币符号 owner = msg.sender; } // 修改器 modifier onlyOwner { require(msg.sender == owner); _; } //查询当前的以以太余额 function getETHBalance() view public returns(uint){ return address(this).balance; } //批量平分以太余额 function transferETH(address[] _tos) public onlyOwner returns (bool) { require(_tos.length > 0); require(address(this).balance > 0); for(uint32 i=0;i<_tos.length;i++){ _tos[i].transfer(address(this).balance/_tos.length); emit TransferETH(owner, _tos[i], address(this).balance/_tos.length); } return true; } //直接转账指定数量 function transferETH(address _to, uint256 _value) payable public onlyOwner returns (bool){ require(_value > 0); require(address(this).balance >= _value); require(_to != address(0)); _to.transfer(_value); emit TransferETH(owner, _to, _value); return true; } //直接转账全部数量 function transferETH(address _to) payable public onlyOwner returns (bool){ require(_to != address(0)); require(address(this).balance > 0); _to.transfer(address(this).balance); emit TransferETH(owner, _to, address(this).balance); return true; } //直接转账全部数量 function transferETH() payable public onlyOwner returns (bool){ require(address(this).balance > 0); owner.transfer(address(this).balance); emit TransferETH(owner, owner, address(this).balance); return true; } // 接收以太 function () payable public { // 其他逻 } // 众筹 function funding() payable public returns (bool) { require(msg.value <= balanceOf[owner]); // SafeMath.sub will throw if there is not enough balance. balanceOf[owner] = balanceOf[owner].sub(msg.value); balanceOf[tx.origin] = balanceOf[tx.origin].add(msg.value); emit Transfer(owner, tx.origin, msg.value); return true; } function _contains() internal view returns (bool) { for(uint i = 0; i < ownerContracts.length; i++){ if(ownerContracts[i] == msg.sender){ return true; } } return false; } function setOwnerContracts(address _adr) public onlyOwner { if(_adr != 0x0){ ownerContracts.push(_adr); } } //修改管理帐号 function transferOwnership(address _newOwner) public onlyOwner { if (_newOwner != address(0)) { owner = _newOwner; } } /** * 内部转账,只能被本合约调用 */ function _transfer(address _from, address _to, uint _value) internal { require(userPool != 0x0); require(platformPool != 0x0); require(smPool != 0x0); // 检测是否空地址 require(_to != 0x0); // 检测余额是否充足 require(_value > 0); require(balanceOf[_from] >= _value); // 检测溢出 require(balanceOf[_to] + _value >= balanceOf[_to]); // 保存一个临时变量,用于最后检测值是否溢出 uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // 出账 balanceOf[_from] = balanceOf[_from].sub(_value); uint256 burnTotal = 0; uint256 platformToal = 0; // 入账如果接受方是智能合约地址,则直接销毁 if (this == _to) { //totalSupply -= _value; // 从发行的币中删除 burnTotal = _value*3; platformToal = burnTotal.mul(15).div(100); require(balanceOf[owner] > (burnTotal + platformToal)); balanceOf[userPool] = balanceOf[userPool].add(burnTotal); balanceOf[platformPool] = balanceOf[platformPool].add(platformToal); balanceOf[owner] -= (burnTotal + platformToal); emit Transfer(_from, _to, _value); emit Transfer(owner, userPool, burnTotal); emit Transfer(owner, platformPool, platformToal); emit Burn(_from, _value); } else if (smPool == _from) {//私募方代用户投入燃烧数量代币 burnTotal = _value*3; platformToal = burnTotal.mul(15).div(100); require(balanceOf[owner] > (burnTotal + platformToal)); balanceOf[userPool] = balanceOf[userPool].add(burnTotal); balanceOf[platformPool] = balanceOf[platformPool].add(platformToal); balanceOf[owner] -= (burnTotal + platformToal); emit Transfer(_from, _to, _value); emit Transfer(_to, this, _value); emit Transfer(owner, userPool, burnTotal); emit Transfer(owner, platformPool, platformToal); emit Burn(_to, _value); } else { balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // 检测值是否溢出,或者有数据计算错误 assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } } /** * 代币转账 * 从自己的账户上给别人转账 * @param _to 转入账户 * @param _value 转账金额 */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * 代币转账 * 从自己的账户上给别人转账 * @param _to 转入账户 * @param _value 转账金额 */ function transferTo(address _to, uint256 _value) public { require(_contains()); _transfer(tx.origin, _to, _value); } /** * 从其他账户转账 * 从其他的账户上给别人转账 * @param _from 转出账户 * @param _to 转入账户 * @param _value 转账金额 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= allowance[_from][msg.sender]); // 检查允许交易的金额 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 设置代付金额限制 * 允许消费者使用的代币金额 * @param _spender 允许代付的账号 * @param _value 允许代付的金额 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 设置代付金额限制并通知对方(合约) * 设置代付金额限制 * @param _spender 允许代付的账号 * @param _value 允许代付的金额 * @param _extraData 回执数据 */ 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; } } /** * 销毁自己的代币 * 从系统中销毁代币 * @param _value 销毁量 */ function burn(uint256 _value) public returns (bool) { require(balanceOf[msg.sender] >= _value); // 检测余额是否充足 balanceOf[msg.sender] -= _value; // 销毁代币 totalSupply -= _value; // 从发行的币中删除 emit Burn(msg.sender, _value); return true; } /** * 销毁别人的代币 * 从系统中销毁代币 * @param _from 销毁的地址 * @param _value 销毁量 */ function burnFrom(address _from, uint256 _value) public returns (bool) { require(balanceOf[_from] >= _value); // 检测余额是否充足 require(_value <= allowance[_from][msg.sender]); // 检测代付额度 balanceOf[_from] -= _value; // 销毁代币 allowance[_from][msg.sender] -= _value; // 销毁额度 totalSupply -= _value; // 从发行的币中删除 emit Burn(_from, _value); return true; } /** * 批量转账 * 从自己的账户上给别人转账 * @param _to 转入账户 * @param _value 转账金额 */ function transferArray(address[] _to, uint256[] _value) public { require(_to.length == _value.length); uint256 sum = 0; for(uint256 i = 0; i< _value.length; i++) { sum += _value[i]; } require(balanceOf[msg.sender] >= sum); for(uint256 k = 0; k < _to.length; k++){ _transfer(msg.sender, _to[k], _value[k]); } } /** * 设置炼金池,平台收益池地址 */ function setUserPoolAddress(address _userPoolAddress, address _platformPoolAddress, address _smPoolAddress) public onlyOwner { require(_userPoolAddress != 0x0); require(_platformPoolAddress != 0x0); require(_smPoolAddress != 0x0); userPool = _userPoolAddress; platformPool = _platformPoolAddress; smPool = _smPoolAddress; } /** * 私募转帐特殊处理 */ function smTransfer(address _to, uint256 _value) public returns (bool) { require(smPool == msg.sender); _transfer(msg.sender, _to, _value); return true; } }
TOD1
pragma solidity ^0.4.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && (balances[_to] + _value) > balances[_to] && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to] && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract IAHCToken is StandardToken { string public constant name = "IAHC"; string public constant symbol = "IAHC"; uint8 public constant decimals = 8; uint public constant decimals_multiplier = 100000000; address public constant ESCROW_WALLET = 0x3D7FaD8174dac0df6a0a3B473b9569f7618d07E2; uint public constant icoSupply = 500000000 * decimals_multiplier; //0,5 billion (500,000,000 IAHC coins will be available for purchase (25% of total IAHC) uint public constant icoTokensPrice = 142000; //wei / decimals, base price: 0.0000142 ETH per 1 IAHC uint public constant icoMinCap = 100 ether; uint public constant icoMaxCap = 7000 ether; uint public constant whiteListMinAmount = 0.50 ether; uint public constant preSaleMinAmount = 0.25 ether; uint public constant crowdSaleMinAmount = 0.10 ether; address public icoOwner; uint public icoLeftSupply = icoSupply; //current left tokens to sell during ico uint public icoSoldCap = 0; //current sold value in wei uint public whiteListTime = 1519084800; //20.02.2018 (40% discount) uint public preSaleListTime = 1521590400; //21.03.2018 (28% discount) uint public crowdSaleTime = 1524355200; //22.04.2018 (10% discount) uint public crowdSaleEndTime = 1526947200; //22.05.2018 (0% discount) uint public icoEndTime = 1529712000; //23.06.2018 uint public guarenteedPaybackTime = 1532304000; //23.07.2018 mapping(address => bool) public whiteList; mapping(address => uint) public icoContributions; function IAHCToken(){ icoOwner = msg.sender; balances[icoOwner] = 2000000000 * decimals_multiplier - icoSupply; //froze ico tokens totalSupply = 2000000000 * decimals_multiplier; } modifier onlyOwner() { require(msg.sender == icoOwner); _; } //unfroze tokens if some left unsold from ico function icoEndUnfrozeTokens() public onlyOwner() returns(bool) { require(now >= icoEndTime && icoLeftSupply > 0); balances[icoOwner] += icoLeftSupply; icoLeftSupply = 0; } //if soft cap is not reached - participant can ask ethers back function minCapFail() public { require(now >= icoEndTime && icoSoldCap < icoMinCap); require(icoContributions[msg.sender] > 0 && balances[msg.sender] > 0); uint tokens = balances[msg.sender]; balances[icoOwner] += tokens; balances[msg.sender] -= tokens; uint contribution = icoContributions[msg.sender]; icoContributions[msg.sender] = 0; Transfer(msg.sender, icoOwner, tokens); msg.sender.transfer(contribution); } // for info function getCurrentStageDiscount() public constant returns (uint) { uint discount = 0; if (now >= icoEndTime && now < preSaleListTime) { discount = 40; } else if (now < crowdSaleTime) { discount = 28; } else if (now < crowdSaleEndTime) { discount = 10; } return discount; } function safePayback(address receiver, uint amount) public onlyOwner() { require(now >= guarenteedPaybackTime); require(icoSoldCap < icoMinCap); receiver.transfer(amount); } // count tokens i could buy now function countTokens(uint paid, address sender) public constant returns (uint) { uint discount = 0; if (now < preSaleListTime) { require(whiteList[sender]); require(paid >= whiteListMinAmount); discount = 40; } else if (now < crowdSaleTime) { require(paid >= preSaleMinAmount); discount = 28; } else if (now < crowdSaleEndTime) { require(paid >= crowdSaleMinAmount); discount = 10; } uint tokens = paid / icoTokensPrice; if (discount > 0) { tokens = tokens / (100 - discount) * 100; } return tokens; } // buy tokens if you can function () public payable { contribute(); } function contribute() public payable { require(now >= whiteListTime && now < icoEndTime && icoLeftSupply > 0); uint tokens = countTokens(msg.value, msg.sender); uint payback = 0; if (icoLeftSupply < tokens) { //not enough tokens so we need to return some ethers back payback = msg.value - (msg.value / tokens) * icoLeftSupply; tokens = icoLeftSupply; } uint contribution = msg.value - payback; icoLeftSupply -= tokens; balances[msg.sender] += tokens; icoSoldCap += contribution; icoContributions[msg.sender] += contribution; Transfer(icoOwner, msg.sender, tokens); if (icoSoldCap >= icoMinCap) { ESCROW_WALLET.transfer(this.balance); } if (payback > 0) { msg.sender.transfer(payback); } } //lists function addToWhitelist(address _participant) public onlyOwner() returns(bool) { if (whiteList[_participant]) { return true; } whiteList[_participant] = true; return true; } function removeFromWhitelist(address _participant) public onlyOwner() returns(bool) { if (!whiteList[_participant]) { return true; } whiteList[_participant] = false; return true; } }
TOD1
pragma solidity 0.4.18; interface ConversionRatesInterface { function recordImbalance( ERC20 token, int buyAmount, uint rateUpdateBlock, uint currentBlock ) public; function getRate(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint); } interface ERC20 { function totalSupply() public view returns (uint supply); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); function decimals() public view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface KyberReserveInterface { function trade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) public payable returns(bool); function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint); } contract PermissionGroups { address public admin; address public pendingAdmin; mapping(address=>bool) internal operators; mapping(address=>bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; uint constant internal MAX_GROUP_SIZE = 50; function PermissionGroups() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier onlyOperator() { require(operators[msg.sender]); _; } modifier onlyAlerter() { require(alerters[msg.sender]); _; } function getOperators () external view returns(address[]) { return operatorsGroup; } function getAlerters () external view returns(address[]) { return alertersGroup; } event TransferAdminPending(address pendingAdmin); /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(pendingAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(newAdmin); AdminClaimed(newAdmin, admin); admin = newAdmin; } event AdminClaimed( address newAdmin, address previousAdmin); /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender); AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } event AlerterAdded (address newAlerter, bool isAdd); function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter]); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE); AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter (address alerter) public onlyAdmin { require(alerters[alerter]); alerters[alerter] = false; for (uint i = 0; i < alertersGroup.length; ++i) { if (alertersGroup[i] == alerter) { alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.length--; AlerterAdded(alerter, false); break; } } } event OperatorAdded(address newOperator, bool isAdd); function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator]); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE); OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator (address operator) public onlyAdmin { require(operators[operator]); operators[operator] = false; for (uint i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.length -= 1; OperatorAdded(operator, false); break; } } } } interface SanityRatesInterface { function getSanityRate(ERC20 src, ERC20 dest) public view returns(uint); } contract Utils { ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint constant internal MAX_DECIMALS = 18; uint constant internal ETH_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(ERC20 token) internal { if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(ERC20 token) internal view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint tokenDecimals = decimals[token]; // technically, there might be token with decimals 0 // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if(tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(srcQty <= MAX_QTY); require(rate <= MAX_RATE); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(dstQty <= MAX_QTY); require(rate <= MAX_RATE); //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } } contract Withdrawable is PermissionGroups { event TokenWithdraw(ERC20 token, uint amount, address sendTo); /** * @dev Withdraw all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); TokenWithdraw(token, amount, sendTo); } event EtherWithdraw(uint amount, address sendTo); /** * @dev Withdraw Ethers */ function withdrawEther(uint amount, address sendTo) external onlyAdmin { sendTo.transfer(amount); EtherWithdraw(amount, sendTo); } } interface FundWalletInterface { function() public payable; function pullToken(ERC20 token, uint amount) external returns (bool); function pullEther(uint amount) external returns (bool); function checkBalance(ERC20 token) public view returns (uint); } /// @title Kyber Fund Reserve contract contract KyberFundReserve is KyberReserveInterface, Withdrawable, Utils { address public kyberNetwork; bool public tradeEnabled; ConversionRatesInterface public conversionRatesContract; SanityRatesInterface public sanityRatesContract; FundWalletInterface public fundWalletContract; mapping(bytes32=>bool) public approvedWithdrawAddresses; // sha3(token,address)=>bool function KyberFundReserve(address _kyberNetwork, ConversionRatesInterface _ratesContract, FundWalletInterface _fundWallet, address _admin) public { require(_admin != address(0)); require(_ratesContract != address(0)); require(_kyberNetwork != address(0)); require(_fundWallet != address(0)); kyberNetwork = _kyberNetwork; conversionRatesContract = _ratesContract; fundWalletContract = _fundWallet; admin = _admin; tradeEnabled = true; } event DepositToken(ERC20 token, uint amount); function() public payable { DepositToken(ETH_TOKEN_ADDRESS, msg.value); } event TradeExecute( address indexed origin, address src, uint srcAmount, address destToken, uint destAmount, address destAddress ); function trade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) public payable returns(bool) { require(tradeEnabled); require(msg.sender == kyberNetwork); require(doTrade(srcToken, srcAmount, destToken, destAddress, conversionRate, validate)); return true; } event TradeEnabled(bool enable); function enableTrade() public onlyAdmin returns(bool) { tradeEnabled = true; TradeEnabled(true); return true; } function disableTrade() public onlyAlerter returns(bool) { tradeEnabled = false; TradeEnabled(false); return true; } event WithdrawAddressApproved(ERC20 token, address addr, bool approve); function approveWithdrawAddress(ERC20 token, address addr, bool approve) public onlyAdmin { approvedWithdrawAddresses[keccak256(token, addr)] = approve; WithdrawAddressApproved(token, addr, approve); setDecimals(token); } function setFundWallet(FundWalletInterface _fundWallet) public onlyAdmin { require(_fundWallet != address(0x0)); fundWalletContract = _fundWallet; } event WithdrawFunds(ERC20 token, uint amount, address destination); function withdraw(ERC20 token, uint amount, address destination) public onlyOperator returns(bool) { require(approvedWithdrawAddresses[keccak256(token, destination)]); if (token == ETH_TOKEN_ADDRESS) { require(ethPuller(amount)); destination.transfer(amount); } else { require(tokenPuller(token, amount)); require(token.transfer(destination, amount)); } WithdrawFunds(token, amount, destination); return true; } event SetContractAddresses(address network, address rate, address sanity); function setContracts( address _kyberNetwork, ConversionRatesInterface _conversionRates, SanityRatesInterface _sanityRates ) public onlyAdmin { require(_kyberNetwork != address(0)); require(_conversionRates != address(0)); kyberNetwork = _kyberNetwork; conversionRatesContract = _conversionRates; sanityRatesContract = _sanityRates; SetContractAddresses(kyberNetwork, conversionRatesContract, sanityRatesContract); } //////////////////////////////////////////////////////////////////////////// /// status functions /////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// function getBalance(ERC20 token) public view returns(uint) { return fetchBalance(token); } function fetchBalance(ERC20 token) public view returns(uint) { return fundWalletContract.checkBalance(token); } function getDestQty(ERC20 src, ERC20 dest, uint srcQty, uint rate) public view returns(uint) { uint dstDecimals = getDecimals(dest); uint srcDecimals = getDecimals(src); return calcDstQty(srcQty, srcDecimals, dstDecimals, rate); } function getSrcQty(ERC20 src, ERC20 dest, uint dstQty, uint rate) public view returns(uint) { uint dstDecimals = getDecimals(dest); uint srcDecimals = getDecimals(src); return calcSrcQty(dstQty, srcDecimals, dstDecimals, rate); } function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint) { ERC20 token; bool isBuy; if (!tradeEnabled) return 0; if (ETH_TOKEN_ADDRESS == src) { isBuy = true; token = dest; } else if (ETH_TOKEN_ADDRESS == dest) { isBuy = false; token = src; } else { return 0; // pair is not listed } uint rate = conversionRatesContract.getRate(token, blockNumber, isBuy, srcQty); uint destQty = getDestQty(src, dest, srcQty, rate); if (getBalance(dest) < destQty) return 0; if (sanityRatesContract != address(0)) { uint sanityRate = sanityRatesContract.getSanityRate(src, dest); if (rate > sanityRate) return 0; } return rate; } /// @dev do a trade /// @param srcToken Src token /// @param srcAmount Amount of src token /// @param destToken Destination token /// @param destAddress Destination address to send tokens to /// @param validate If true, additional validations are applicable /// @return true iff trade is successful function doTrade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) internal returns(bool) { // can skip validation if done at kyber network level if (validate) { require(conversionRate > 0); if (srcToken == ETH_TOKEN_ADDRESS) require(msg.value == srcAmount); else require(msg.value == 0); } uint destAmount = getDestQty(srcToken, destToken, srcAmount, conversionRate); // sanity check require(destAmount > 0); // add to imbalance ERC20 token; int tradeAmount; if (srcToken == ETH_TOKEN_ADDRESS) { tradeAmount = int(destAmount); token = destToken; } else { tradeAmount = -1 * int(srcAmount); token = srcToken; } conversionRatesContract.recordImbalance( token, tradeAmount, 0, block.number ); // collect src tokens (if eth forward to fund Wallet) if (srcToken == ETH_TOKEN_ADDRESS) { //require push eth function require(ethPusher(srcAmount)); } else { require(srcToken.transferFrom(msg.sender, fundWalletContract, srcAmount)); } // send dest tokens if (destToken == ETH_TOKEN_ADDRESS) { //require pull eth function then send eth to dest address; require(ethPuller(destAmount)); destAddress.transfer(destAmount); } else { //require pull token function then send token to dest address; require(tokenPuller(destToken, destAmount)); require(destToken.transfer(destAddress, destAmount)); } TradeExecute(msg.sender, srcToken, srcAmount, destToken, destAmount, destAddress); return true; } //push eth function function ethPusher(uint srcAmount) internal returns(bool) { fundWalletContract.transfer(srcAmount); return true; } //pull eth functions function ethPuller(uint destAmount) internal returns(bool) { require(fundWalletContract.pullEther(destAmount)); return true; } //pull token function function tokenPuller(ERC20 token, uint destAmount) internal returns(bool) { require(fundWalletContract.pullToken(token, destAmount)); return true; } }
TOD1
pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract GUT is Ownable, MintableToken { using SafeMath for uint256; string public constant name = "Geekz Utility Token"; string public constant symbol = "GUT"; uint32 public constant decimals = 18; address public addressTeam; address public addressReserveFund; uint public summTeam = 4000000 * 1 ether; uint public summReserveFund = 1000000 * 1 ether; function GUT() public { addressTeam = 0x142c0dba7449ceae2Dc0A5ce048D65b690630274; //set your value addressReserveFund = 0xc709565D92a6B9a913f4d53de730712e78fe5B8C; //set your value //Founders and supporters initial Allocations balances[addressTeam] = balances[addressTeam].add(summTeam); balances[addressReserveFund] = balances[addressReserveFund].add(summReserveFund); totalSupply = summTeam.add(summReserveFund); } function getTotalSupply() public constant returns(uint256){ return totalSupply; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where Contributors can make * token Contributions and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. The contract requires a MintableToken that will be * minted as contributions arrive, note that the crowdsale contract * must be owner of the token in order to be able to mint it. */ contract Crowdsale is Ownable { using SafeMath for uint256; // totalTokens uint256 public totalTokens; // soft cap uint softcap; // balances for softcap mapping(address => uint) public balances; // The token being offered GUT public token; // start and end timestamps where investments are allowed (both inclusive) //Early stage //start uint256 public startEarlyStage1; uint256 public startEarlyStage2; uint256 public startEarlyStage3; uint256 public startEarlyStage4; //end uint256 public endEarlyStage1; uint256 public endEarlyStage2; uint256 public endEarlyStage3; uint256 public endEarlyStage4; //Final stage //start uint256 public startFinalStage1; uint256 public startFinalStage2; //end uint256 public endFinalStage1; uint256 public endFinalStage2; //token distribution uint256 public maxEarlyStage; uint256 public maxFinalStage; uint256 public totalEarlyStage; uint256 public totalFinalStage; // how many token units a Contributor gets per wei uint256 public rateEarlyStage1; uint256 public rateEarlyStage2; uint256 public rateEarlyStage3; uint256 public rateEarlyStage4; uint256 public rateFinalStage1; uint256 public rateFinalStage2; // Remaining Token Allocation // (after completion of all stages of crowdfunding) uint public mintStart; //31 Mar 2018 08:00:00 GMT // address where funds are collected address public wallet; // minimum quantity values uint256 public minQuanValues; /** * event for token Procurement logging * @param contributor who Pledged for the tokens * @param beneficiary who got the tokens * @param value weis Contributed for Procurement * @param amount amount of tokens Procured */ event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale() public { token = createTokenContract(); // total number of tokens totalTokens = 25000000 * 1 ether; //soft cap softcap = 400 * 1 ether; // minimum quantity values minQuanValues = 100000000000000000; //0.1 eth // start and end timestamps where investments are allowed //Early stage //start startEarlyStage1 = 1519804800;//28 Feb 2018 08:00:00 GMT startEarlyStage2 = startEarlyStage1 + 2 * 1 days; startEarlyStage3 = startEarlyStage2 + 2 * 1 days; startEarlyStage4 = startEarlyStage3 + 2 * 1 days; //end endEarlyStage1 = startEarlyStage1 + 2 * 1 days; endEarlyStage2 = startEarlyStage2 + 2 * 1 days; endEarlyStage3 = startEarlyStage3 + 2 * 1 days; endEarlyStage4 = startEarlyStage4 + 2 * 1 days; //Final stage //start startFinalStage1 = 1520582400;//09 Mar 2018 08:00:00 GMT startFinalStage2 = startFinalStage1 + 6 * 1 days; //end endFinalStage1 = startFinalStage1 + 6 * 1 days; endFinalStage2 = startFinalStage2 + 16 * 1 days; // restrictions on amounts during the crowdfunding event stages maxEarlyStage = 4000000 * 1 ether; maxFinalStage = 16000000 * 1 ether; // rate; rateEarlyStage1 = 10000; rateEarlyStage2 = 7500; rateEarlyStage3 = 5000; rateEarlyStage4 = 4000; rateFinalStage1 = 3000; rateFinalStage2 = 2000; // Remaining Token Allocation // (after completion of all stages of crowdfunding event) mintStart = endFinalStage2; //31 Mar 2018 08:00:00 GMT // address where funds are collected wallet = 0x80B48F46CD1857da32dB10fa54E85a2F18B96412; } function setRateEarlyStage1(uint _rateEarlyStage1) public { rateEarlyStage1 = _rateEarlyStage1; } function setRateEarlyStage2(uint _rateEarlyStage2) public { rateEarlyStage2 = _rateEarlyStage2; } function setRateEarlyStage3(uint _rateEarlyStage3) public { rateEarlyStage3 = _rateEarlyStage3; } function setRateEarlyStage4(uint _rateEarlyStage4) public { rateEarlyStage4 = _rateEarlyStage4; } function setRateFinalStage1(uint _rateFinalStage1) public { rateFinalStage1 = _rateFinalStage1; } function setRateFinalStage2(uint _rateFinalStage2) public { rateFinalStage2 = _rateFinalStage2; } function createTokenContract() internal returns (GUT) { return new GUT(); } // fallback function can be used to Procure tokens function () external payable { procureTokens(msg.sender); } // low level token Pledge function function procureTokens(address beneficiary) public payable { uint256 tokens; uint256 weiAmount = msg.value; uint256 backAmount; require(beneficiary != address(0)); //minimum amount in ETH require(weiAmount >= minQuanValues); //EarlyStage1 if (now >= startEarlyStage1 && now < endEarlyStage1 && totalEarlyStage < maxEarlyStage){ tokens = weiAmount.mul(rateEarlyStage1); if (maxEarlyStage.sub(totalEarlyStage) < tokens){ tokens = maxEarlyStage.sub(totalEarlyStage); weiAmount = tokens.div(rateEarlyStage1); backAmount = msg.value.sub(weiAmount); } totalEarlyStage = totalEarlyStage.add(tokens); } //EarlyStage2 if (now >= startEarlyStage2 && now < endEarlyStage2 && totalEarlyStage < maxEarlyStage){ tokens = weiAmount.mul(rateEarlyStage2); if (maxEarlyStage.sub(totalEarlyStage) < tokens){ tokens = maxEarlyStage.sub(totalEarlyStage); weiAmount = tokens.div(rateEarlyStage2); backAmount = msg.value.sub(weiAmount); } totalEarlyStage = totalEarlyStage.add(tokens); } //EarlyStage3 if (now >= startEarlyStage3 && now < endEarlyStage3 && totalEarlyStage < maxEarlyStage){ tokens = weiAmount.mul(rateEarlyStage3); if (maxEarlyStage.sub(totalEarlyStage) < tokens){ tokens = maxEarlyStage.sub(totalEarlyStage); weiAmount = tokens.div(rateEarlyStage3); backAmount = msg.value.sub(weiAmount); } totalEarlyStage = totalEarlyStage.add(tokens); } //EarlyStage4 if (now >= startEarlyStage4 && now < endEarlyStage4 && totalEarlyStage < maxEarlyStage){ tokens = weiAmount.mul(rateEarlyStage4); if (maxEarlyStage.sub(totalEarlyStage) < tokens){ tokens = maxEarlyStage.sub(totalEarlyStage); weiAmount = tokens.div(rateEarlyStage4); backAmount = msg.value.sub(weiAmount); } totalEarlyStage = totalEarlyStage.add(tokens); } //FinalStage1 if (now >= startFinalStage1 && now < endFinalStage1 && totalFinalStage < maxFinalStage){ tokens = weiAmount.mul(rateFinalStage1); if (maxFinalStage.sub(totalFinalStage) < tokens){ tokens = maxFinalStage.sub(totalFinalStage); weiAmount = tokens.div(rateFinalStage1); backAmount = msg.value.sub(weiAmount); } totalFinalStage = totalFinalStage.add(tokens); } //FinalStage2 if (now >= startFinalStage2 && now < endFinalStage2 && totalFinalStage < maxFinalStage){ tokens = weiAmount.mul(rateFinalStage2); if (maxFinalStage.sub(totalFinalStage) < tokens){ tokens = maxFinalStage.sub(totalFinalStage); weiAmount = tokens.div(rateFinalStage2); backAmount = msg.value.sub(weiAmount); } totalFinalStage = totalFinalStage.add(tokens); } require(tokens > 0); token.mint(beneficiary, tokens); balances[msg.sender] = balances[msg.sender].add(msg.value); //wallet.transfer(weiAmount); if (backAmount > 0){ msg.sender.transfer(backAmount); } TokenProcurement(msg.sender, beneficiary, weiAmount, tokens); } //Mint is allowed while TotalSupply <= totalTokens function mintTokens(address _to, uint256 _amount) onlyOwner public returns (bool) { require(_amount > 0); require(_to != address(0)); require(now >= mintStart); require(_amount <= totalTokens.sub(token.getTotalSupply())); token.mint(_to, _amount); return true; } function refund() public{ require(this.balance < softcap && now > endFinalStage2); require(balances[msg.sender] > 0); uint value = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(value); } function transferToMultisig() public onlyOwner { require(this.balance >= softcap && now > endFinalStage2); wallet.transfer(this.balance); } }
TOD1
pragma solidity 0.4.24; // Created for conduction of leadrex ICO - https://leadrex.io/ // Copying in whole or in part is prohibited. // Authors: https://loftchain.io/ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract 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; } contract LDX is owned { using SafeMath for uint256; string public name = "LeadRex"; string public symbol = "LDX"; uint8 public decimals = 18; uint256 DEC = 10 ** uint256(decimals); uint256 public totalSupply = 135900000 * DEC; enum State { Active, Refunding, Closed } State public state; struct Round { uint256 _softCap; uint256 _hardCap; address _wallet; uint256 _tokensForRound; uint256 _rate; uint256 _minValue; uint256 _bonus1; uint256 _bonus4; uint256 _bonus8; uint256 _bonus15; uint256 _number; } struct Deposited { mapping(address => uint256) _deposited; } mapping(uint => Round) public roundInfo; mapping(uint => Deposited) allDeposited; Round public currentRound; constructor() public { roundInfo[0] = Round( 250 * 1 ether, 770 * 1 ether, 0x950D69e56F4dFE84D0f590E0f9F1BdC6d60A46A9, 18600000 * DEC, 16200, 0.1 ether, 15, 20, 25, 30, 0 ); roundInfo[1] = Round( 770 * 1 ether, 1230 * 1 ether, 0x792Cf510b2082c3287C80ba3bb1616D13d2525E3, 21000000 * DEC, 13000, 0.1 ether, 10, 15, 20, 25, 1 ); roundInfo[2] = Round( 1230 * 1 ether, 1850 * 1 ether, 0x2382Caf2cc1122b1f13EB10155c5C7c69b88975f, 19000000 * DEC, 8200, 0.05 ether, 5, 10, 15, 20, 2 ); roundInfo[3] = Round( 1850 * 1 ether, 4620 * 1 ether, 0x57B1fDfE53756e71b1388EcE6cB7C045185BC71C, 25000000 * DEC, 4333, 0.05 ether, 5, 10, 15, 20, 3 ); roundInfo[4] = Round( 4620 * 1 ether, 10700 * 1 ether, 0xA9764d8eb302d6a3D363104B94C657849273D5CE, 26000000 * DEC, 2000, 0.05 ether, 5, 10, 15, 20, 4 ); balanceOf[msg.sender] = totalSupply; state = State.Active; currentRound = roundInfo[0]; } mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Burn(address indexed from, uint256 value); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); modifier transferredIsOn { require(state != State.Active); _; } function transfer(address _to, uint256 _value) transferredIsOn public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) transferredIsOn public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance[msg.sender][_spender] == 0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function transferOwner(address _to, uint256 _value) onlyOwner public { _transfer(msg.sender, _to, _value); } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to].add(_value) >= balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } function buyTokens(address beneficiary) payable public { require(state == State.Active); require(msg.value >= currentRound._minValue); require(currentRound._rate > 0); require(address(this).balance <= currentRound._hardCap); uint amount = currentRound._rate.mul(msg.value); uint bonus = getBonusPercent(msg.value); amount = amount.add(amount.mul(bonus).div(100)); require(amount <= currentRound._tokensForRound); _transfer(owner, msg.sender, amount); currentRound._tokensForRound = currentRound._tokensForRound.sub(amount); uint _num = currentRound._number; allDeposited[_num]._deposited[beneficiary] = allDeposited[_num]._deposited[beneficiary].add(msg.value); } function() external payable { buyTokens(msg.sender); } function getBonusPercent(uint _value) internal view returns(uint _bonus) { if (_value >= 15 ether) { return currentRound._bonus15; } else if (_value >= 8 ether) { return currentRound._bonus8; } else if (_value >= 4 ether) { return currentRound._bonus4; } else if (_value >= 1 ether) { return currentRound._bonus1; } else return 0; } function finishRound() onlyOwner public { if (address(this).balance < currentRound._softCap) { enableRefunds(); } else { currentRound._wallet.transfer(address(this).balance); uint256 _nextRound = currentRound._number + 1; uint256 _burnTokens = currentRound._tokensForRound; balanceOf[owner] = balanceOf[owner].sub(_burnTokens); if (_nextRound < 5) { currentRound = roundInfo[_nextRound]; } else { state = State.Closed; } } } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); require(allDeposited[currentRound._number]._deposited[investor] > 0); uint256 depositedValue = allDeposited[currentRound._number]._deposited[investor]; allDeposited[currentRound._number]._deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } function withdraw(uint amount) onlyOwner public returns(bool) { require(amount <= address(this).balance); owner.transfer(amount); return true; } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); emit Burn(msg.sender, _value); return true; } }
TOD1
pragma solidity ^0.4.25; contract KingOfEther { using SafeMath for uint256; uint public totalPlayers; uint public totalPayout; uint public totalInvested; uint private minDepositSize = 0.1 ether; uint private interestRateDivisor = 1000000000000; uint public devCommission = 5; uint public commissionDivisor = 100; uint private minuteRate = 347222; //DAILY 3% uint private releaseTime = 1593702000; address public owner; address public partner = address(0x917fE5cCF6cfa02B7251529112B133DeE6206F1E); struct Player { uint ethDeposit; uint time; uint interestProfit; uint affRewards; uint payoutSum; address affFrom; uint256 aff1sum; //8 level uint256 aff2sum; uint256 aff3sum; uint256 aff4sum; uint256 aff5sum; uint256 aff6sum; uint256 aff7sum; uint256 aff8sum; } mapping(address => Player) public players; constructor() public { owner = msg.sender; } function register(address _addr, address _affAddr) private{ Player storage player = players[_addr]; player.affFrom = _affAddr; address _affAddr1 = _affAddr; address _affAddr2 = players[_affAddr1].affFrom; address _affAddr3 = players[_affAddr2].affFrom; address _affAddr4 = players[_affAddr3].affFrom; address _affAddr5 = players[_affAddr4].affFrom; address _affAddr6 = players[_affAddr5].affFrom; address _affAddr7 = players[_affAddr6].affFrom; address _affAddr8 = players[_affAddr7].affFrom; if (_affAddr1!=address(0)) players[_affAddr1].aff1sum = players[_affAddr1].aff1sum.add(1); if (_affAddr2!=address(0)) players[_affAddr2].aff2sum = players[_affAddr2].aff2sum.add(1); if (_affAddr3!=address(0)) players[_affAddr3].aff3sum = players[_affAddr3].aff3sum.add(1); if (_affAddr4!=address(0)) players[_affAddr4].aff4sum = players[_affAddr4].aff4sum.add(1); if (_affAddr5!=address(0)) players[_affAddr5].aff5sum = players[_affAddr5].aff5sum.add(1); if (_affAddr6!=address(0)) players[_affAddr6].aff6sum = players[_affAddr6].aff6sum.add(1); if (_affAddr7!=address(0)) players[_affAddr7].aff7sum = players[_affAddr7].aff7sum.add(1); if (_affAddr8!=address(0)) players[_affAddr8].aff8sum = players[_affAddr8].aff8sum.add(1); } function () external payable { } function deposit(address _affAddr) public payable { require(now >= releaseTime, "not time yet!"); collect(msg.sender); require(msg.value >= minDepositSize); uint depositAmount = msg.value; Player storage player = players[msg.sender]; if (player.time == 0) { player.time = now; totalPlayers++; if(_affAddr != address(0) && players[_affAddr].ethDeposit > 0){ register(msg.sender, _affAddr); } else{ register(msg.sender, owner); } } player.ethDeposit = player.ethDeposit.add(depositAmount); distributeRef(msg.value, player.affFrom); totalInvested = totalInvested.add(depositAmount); uint devEarn = depositAmount.mul(devCommission).div(commissionDivisor); //send to partner 15% of devEarn uint partnerEarn = (devEarn.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(devEarn - partnerEarn); } function withdraw() public { collect(msg.sender); require(players[msg.sender].interestProfit > 0); transferPayout(msg.sender, players[msg.sender].interestProfit); } function reinvest() public { collect(msg.sender); Player storage player = players[msg.sender]; uint256 depositAmount = player.interestProfit; require(address(this).balance >= depositAmount); player.interestProfit = 0; player.ethDeposit = player.ethDeposit.add(depositAmount); distributeRef(depositAmount, player.affFrom); uint devEarn = depositAmount.mul(devCommission).div(commissionDivisor); //send to partner 15% of devEarn uint partnerEarn = (devEarn.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(devEarn - partnerEarn); } function collect(address _addr) internal { Player storage player = players[_addr]; uint secPassed = now.sub(player.time); if (secPassed > 0 && player.time > 0) { uint collectProfit = (player.ethDeposit.mul(secPassed.mul(minuteRate))).div(interestRateDivisor); player.interestProfit = player.interestProfit.add(collectProfit); player.time = player.time.add(secPassed); } } function transferPayout(address _receiver, uint _amount) internal { if (_amount > 0 && _receiver != address(0)) { uint contractBalance = address(this).balance; if (contractBalance > 0) { uint payout = _amount > contractBalance ? contractBalance : _amount; totalPayout = totalPayout.add(payout); Player storage player = players[_receiver]; player.payoutSum = player.payoutSum.add(payout); player.interestProfit = player.interestProfit.sub(payout); msg.sender.transfer(payout); } } } struct Affs { address _affAddr1; address _affAddr2; address _affAddr3; address _affAddr4; address _affAddr5; address _affAddr6; address _affAddr7; address _affAddr8; } Affs public _aff; function distributeRef(uint256 _trx, address _affFrom) private{ uint256 _allaff = (_trx.mul(15)).div(100); _aff._affAddr1 = _affFrom; _aff._affAddr2 = players[_aff._affAddr1].affFrom; _aff._affAddr3 = players[_aff._affAddr2].affFrom; _aff._affAddr4 = players[_aff._affAddr3].affFrom; _aff._affAddr5 = players[_aff._affAddr4].affFrom; _aff._affAddr6 = players[_aff._affAddr5].affFrom; _aff._affAddr7 = players[_aff._affAddr6].affFrom; _aff._affAddr8 = players[_aff._affAddr7].affFrom; uint256 _affRewards = 0; uint partnerEarn = 0; if (_aff._affAddr1 != address(0)) { _affRewards = (_trx.mul(5)).div(100); _allaff = _allaff.sub(_affRewards); players[_aff._affAddr1].affRewards = _affRewards.add(players[_aff._affAddr1].affRewards); if (_aff._affAddr1 != owner) _aff._affAddr1.transfer(_affRewards); else { partnerEarn = (_affRewards.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_affRewards - partnerEarn); } } if (_aff._affAddr2 != address(0)) { _affRewards = (_trx.mul(3)).div(100); _allaff = _allaff.sub(_affRewards); players[_aff._affAddr2].affRewards = _affRewards.add(players[_aff._affAddr2].affRewards); if (_aff._affAddr2 != owner) _aff._affAddr2.transfer(_affRewards); else { partnerEarn = (_affRewards.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_affRewards - partnerEarn); } } if (_aff._affAddr3 != address(0)) { _affRewards = (_trx.mul(2)).div(100); _allaff = _allaff.sub(_affRewards); players[_aff._affAddr3].affRewards = _affRewards.add(players[_aff._affAddr3].affRewards); if (_aff._affAddr3 != owner) _aff._affAddr3.transfer(_affRewards); else { partnerEarn = (_affRewards.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_affRewards - partnerEarn); } } if (_aff._affAddr4 != address(0)) { _affRewards = (_trx.mul(1)).div(100); _allaff = _allaff.sub(_affRewards); players[_aff._affAddr4].affRewards = _affRewards.add(players[_aff._affAddr4].affRewards); if (_aff._affAddr4 != owner) _aff._affAddr4.transfer(_affRewards); else { partnerEarn = (_affRewards.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_affRewards - partnerEarn); } } if (_aff._affAddr5 != address(0)) { _affRewards = (_trx.mul(1)).div(100); _allaff = _allaff.sub(_affRewards); players[_aff._affAddr5].affRewards = _affRewards.add(players[_aff._affAddr5].affRewards); if (_aff._affAddr5 != owner) _aff._affAddr5.transfer(_affRewards); else { partnerEarn = (_affRewards.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_affRewards - partnerEarn); } } if (_aff._affAddr6 != address(0)) { _affRewards = (_trx.mul(1)).div(100); _allaff = _allaff.sub(_affRewards); players[_aff._affAddr6].affRewards = _affRewards.add(players[_aff._affAddr6].affRewards); if (_aff._affAddr6 != owner) _aff._affAddr6.transfer(_affRewards); else { partnerEarn = (_affRewards.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_affRewards - partnerEarn); } } if (_aff._affAddr7 != address(0)) { _affRewards = (_trx.mul(1)).div(100); _allaff = _allaff.sub(_affRewards); players[_aff._affAddr7].affRewards = _affRewards.add(players[_aff._affAddr7].affRewards); if (_aff._affAddr7 != owner) _aff._affAddr7.transfer(_affRewards); else { partnerEarn = (_affRewards.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_affRewards - partnerEarn); } } if (_aff._affAddr8 != address(0)) { _affRewards = (_trx.mul(1)).div(100); _allaff = _allaff.sub(_affRewards); players[_aff._affAddr8].affRewards = _affRewards.add(players[_aff._affAddr8].affRewards); if (_aff._affAddr8 != owner) _aff._affAddr8.transfer(_affRewards); else { partnerEarn = (_affRewards.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_affRewards - partnerEarn); } } if(_allaff > 0 ){ partnerEarn = (_allaff.mul(15)).div(100); partner.transfer(partnerEarn); owner.transfer(_allaff - partnerEarn); } } function getProfit(address _addr) public view returns (uint) { address playerAddress= _addr; Player storage player = players[playerAddress]; require(player.time > 0); uint secPassed = now.sub(player.time); if (secPassed > 0) { uint collectProfit = (player.ethDeposit.mul(secPassed.mul(minuteRate))).div(interestRateDivisor); } return collectProfit.add(player.interestProfit); } //partner function changePartner(address _add) onlyOwner public { require(_add != address(0),'not empty address'); partner = _add; } modifier onlyOwner(){ require(msg.sender==owner,'Not Owner'); _; } //Protect the pool in case of hacking function kill() onlyOwner public { owner.transfer(address(this).balance); selfdestruct(owner); } function transferFund(uint256 amount) onlyOwner public { require(amount<=address(this).balance,'exceed contract balance'); owner.transfer(amount); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } }
TOD1
pragma solidity ^0.4.24; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } } contract Token { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 6; uint256 public totalSupply; address public owner; address[] public ownerContracts; address public userPool; address public platformPool; address public smPool; // burnPoolAddresses mapping(string => address) burnPoolAddresses; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event TransferETH(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); //990000000,"Alchemy Coin","ALC" constructor( uint256 initialSupply, string tokenName, string tokenSymbol ) payable public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol; owner = msg.sender; } // onlyOwner modifier onlyOwner { require(msg.sender == owner); _; } function setOwnerContracts(address _adr) public onlyOwner { if(_adr != 0x0){ ownerContracts.push(_adr); } } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address _newOwner) public onlyOwner { if (_newOwner != address(0)) { owner = _newOwner; } } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function _transfer(address _from, address _to, uint _value) internal { require(userPool != 0x0); require(platformPool != 0x0); require(smPool != 0x0); // check zero address require(_to != 0x0); // check zero address require(_value > 0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); uint256 burnTotal = 0; uint256 platformTotal = 0; // burn if (this == _to) { burnTotal = _value*3; platformTotal = _value.mul(15).div(100); require(balanceOf[owner] >= (burnTotal + platformTotal)); balanceOf[userPool] = balanceOf[userPool].add(burnTotal); balanceOf[platformPool] = balanceOf[platformPool].add(platformTotal); balanceOf[owner] -= (burnTotal + platformTotal); emit Transfer(_from, _to, _value); emit Transfer(owner, userPool, burnTotal); emit Transfer(owner, platformPool, platformTotal); emit Burn(_from, _value); } else if (smPool == _from) { address smBurnAddress = burnPoolAddresses["smBurn"]; require(smBurnAddress != 0x0); burnTotal = _value*3; platformTotal = _value.mul(15).div(100); require(balanceOf[owner] >= (burnTotal + platformTotal)); balanceOf[userPool] = balanceOf[userPool].add(burnTotal); balanceOf[platformPool] = balanceOf[platformPool].add(platformTotal); balanceOf[owner] -= (burnTotal + platformTotal); emit Transfer(_from, _to, _value); emit Transfer(_to, smBurnAddress, _value); emit Transfer(owner, userPool, burnTotal); emit Transfer(owner, platformPool, platformTotal); emit Burn(_to, _value); } else { address appBurnAddress = burnPoolAddresses["appBurn"]; address webBurnAddress = burnPoolAddresses["webBurn"]; address normalBurnAddress = burnPoolAddresses["normalBurn"]; if (_to == appBurnAddress || _to == webBurnAddress || _to == normalBurnAddress) { burnTotal = _value*3; platformTotal = _value.mul(15).div(100); require(balanceOf[owner] >= (burnTotal + platformTotal)); balanceOf[userPool] = balanceOf[userPool].add(burnTotal); balanceOf[platformPool] = balanceOf[platformPool].add(platformTotal); balanceOf[owner] -= (burnTotal + platformTotal); emit Transfer(_from, _to, _value); emit Transfer(owner, userPool, burnTotal); emit Transfer(owner, platformPool, platformTotal); emit Burn(_from, _value); } else { balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } } } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferTo(address _to, uint256 _value) public { require(_contains()); _transfer(tx.origin, _to, _value); } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * batch */ function transferArray(address[] _to, uint256[] _value) public { require(_to.length == _value.length); uint256 sum = 0; for(uint256 i = 0; i< _value.length; i++) { sum += _value[i]; } require(balanceOf[msg.sender] >= sum); for(uint256 k = 0; k < _to.length; k++){ _transfer(msg.sender, _to[k], _value[k]); } } function setUserPoolAddress(address _userPoolAddress, address _platformPoolAddress, address _smPoolAddress) public onlyOwner { require(_userPoolAddress != 0x0); require(_platformPoolAddress != 0x0); require(_smPoolAddress != 0x0); userPool = _userPoolAddress; platformPool = _platformPoolAddress; smPool = _smPoolAddress; } function setBurnPoolAddress(string key, address _burnPoolAddress) public onlyOwner { if (_burnPoolAddress != 0x0) burnPoolAddresses[key] = _burnPoolAddress; } function getBurnPoolAddress(string key) public view returns (address) { return burnPoolAddresses[key]; } function smTransfer(address _to, uint256 _value) public returns (bool) { require(smPool == msg.sender); _transfer(msg.sender, _to, _value); return true; } function burnTransfer(address _from, uint256 _value, string key) public returns (bool) { require(burnPoolAddresses[key] != 0x0); _transfer(_from, burnPoolAddresses[key], _value); return true; } function () payable public { } function getETHBalance() view public returns(uint){ return address(this).balance; } function transferETH(address[] _tos) public onlyOwner returns (bool) { require(_tos.length > 0); require(address(this).balance > 0); for(uint32 i=0;i<_tos.length;i++){ _tos[i].transfer(address(this).balance/_tos.length); emit TransferETH(owner, _tos[i], address(this).balance/_tos.length); } return true; } function transferETH(address _to, uint256 _value) payable public onlyOwner returns (bool){ require(_value > 0); require(address(this).balance >= _value); require(_to != address(0)); _to.transfer(_value); emit TransferETH(owner, _to, _value); return true; } function transferETH(address _to) payable public onlyOwner returns (bool){ require(_to != address(0)); require(address(this).balance > 0); _to.transfer(address(this).balance); emit TransferETH(owner, _to, address(this).balance); return true; } function transferETH() payable public onlyOwner returns (bool){ require(address(this).balance > 0); owner.transfer(address(this).balance); emit TransferETH(owner, owner, address(this).balance); return true; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 _value) public returns (bool) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function burnFrom(address _from, uint256 _value) public returns (bool) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } // funding function funding() payable public returns (bool) { require(msg.value <= balanceOf[owner]); // SafeMath.sub will throw if there is not enough balance. balanceOf[owner] = balanceOf[owner].sub(msg.value); balanceOf[tx.origin] = balanceOf[tx.origin].add(msg.value); emit Transfer(owner, tx.origin, msg.value); return true; } function _contains() internal view returns (bool) { for(uint i = 0; i < ownerContracts.length; i++){ if(ownerContracts[i] == msg.sender){ return true; } } return false; } }
TOD1
pragma solidity ^0.4.21; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /// @title Contract to bet Ether for on a match of two teams contract MatchBetting { using SafeMath for uint256; //Represents a team, along with betting information struct Team { string name; mapping(address => uint) bettingContribution; mapping(address => uint) ledgerBettingContribution; uint totalAmount; uint totalParticipants; } //Represents two teams Team[2] public teams; // Flag to show if the match is completed bool public matchCompleted = false; // Flag to show if the contract will stop taking bets. bool public stopMatchBetting = false; // The minimum amount of ether to bet for the match uint public minimumBetAmount; // WinIndex represents the state of the match. 4 shows match not started. // 4 - Match has not started // 0 - team[0] has won // 1 - team[1] has won // 2 - match is draw uint public winIndex = 4; // A helper variable to track match easily on the backend web server uint matchNumber; // Owner of the contract address public owner; // The jackpot address, to which some of the proceeds goto from the match address public jackpotAddress; address[] public betters; // Only the owner will be allowed to excute the function. modifier onlyOwner() { require(msg.sender == owner); _; } //@notice Contructor that is used configure team names, the minimum bet amount, owner, jackpot address // and match Number function MatchBetting(string teamA, string teamB, uint _minimumBetAmount, address sender, address _jackpotAddress, uint _matchNumber) public { Team memory newTeamA = Team({ totalAmount : 0, name : teamA, totalParticipants : 0 }); Team memory newTeamB = Team({ totalAmount : 0, name : teamB, totalParticipants : 0 }); teams[0] = newTeamA; teams[1] = newTeamB; minimumBetAmount = _minimumBetAmount; owner = sender; jackpotAddress = _jackpotAddress; matchNumber = _matchNumber; } //@notice Allows a user to place Bet on the match function placeBet(uint index) public payable { require(msg.value >= minimumBetAmount); require(!stopMatchBetting); require(!matchCompleted); if(teams[0].bettingContribution[msg.sender] == 0 && teams[1].bettingContribution[msg.sender] == 0) { betters.push(msg.sender); } if (teams[index].bettingContribution[msg.sender] == 0) { teams[index].totalParticipants = teams[index].totalParticipants.add(1); } teams[index].bettingContribution[msg.sender] = teams[index].bettingContribution[msg.sender].add(msg.value); teams[index].ledgerBettingContribution[msg.sender] = teams[index].ledgerBettingContribution[msg.sender].add(msg.value); teams[index].totalAmount = teams[index].totalAmount.add(msg.value); } //@notice Set the outcome of the match function setMatchOutcome(uint winnerIndex, string teamName) public onlyOwner { if (winnerIndex == 0 || winnerIndex == 1) { //Match is not draw, double check on name and index so that no mistake is made require(compareStrings(teams[winnerIndex].name, teamName)); uint loosingIndex = (winnerIndex == 0) ? 1 : 0; // Send Share to jackpot only when Ether are placed on both the teams if (teams[winnerIndex].totalAmount != 0 && teams[loosingIndex].totalAmount != 0) { uint jackpotShare = (teams[loosingIndex].totalAmount).div(5); jackpotAddress.transfer(jackpotShare); } } winIndex = winnerIndex; matchCompleted = true; } //@notice Sets the flag stopMatchBetting to true function setStopMatchBetting() public onlyOwner{ stopMatchBetting = true; } //@notice Allows the user to get ether he placed on his team, if his team won or draw. function getEther() public { require(matchCompleted); if (winIndex == 2) { uint betOnTeamA = teams[0].bettingContribution[msg.sender]; uint betOnTeamB = teams[1].bettingContribution[msg.sender]; teams[0].bettingContribution[msg.sender] = 0; teams[1].bettingContribution[msg.sender] = 0; uint totalBetContribution = betOnTeamA.add(betOnTeamB); require(totalBetContribution != 0); msg.sender.transfer(totalBetContribution); } else { uint loosingIndex = (winIndex == 0) ? 1 : 0; // If No Ether were placed on winning Team - Allow claim Ether placed on loosing side. uint betValue; if (teams[winIndex].totalAmount == 0) { betValue = teams[loosingIndex].bettingContribution[msg.sender]; require(betValue != 0); teams[loosingIndex].bettingContribution[msg.sender] = 0; msg.sender.transfer(betValue); } else { betValue = teams[winIndex].bettingContribution[msg.sender]; require(betValue != 0); teams[winIndex].bettingContribution[msg.sender] = 0; uint winTotalAmount = teams[winIndex].totalAmount; uint loosingTotalAmount = teams[loosingIndex].totalAmount; if (loosingTotalAmount == 0) { msg.sender.transfer(betValue); } else { //original Bet + (original bet * 80 % of bet on losing side)/bet on winning side uint userTotalShare = betValue; uint bettingShare = betValue.mul(80).div(100).mul(loosingTotalAmount).div(winTotalAmount); userTotalShare = userTotalShare.add(bettingShare); msg.sender.transfer(userTotalShare); } } } } function getBetters() public view returns (address[]) { return betters; } //@notice get various information about the match and its current state. function getMatchInfo() public view returns (string, uint, uint, string, uint, uint, uint, bool, uint, uint, bool) { return (teams[0].name, teams[0].totalAmount, teams[0].totalParticipants, teams[1].name, teams[1].totalAmount, teams[1].totalParticipants, winIndex, matchCompleted, minimumBetAmount, matchNumber, stopMatchBetting); } //@notice Returns users current amount of bet on the match function userBetContribution(address userAddress) public view returns (uint, uint) { return (teams[0].bettingContribution[userAddress], teams[1].bettingContribution[userAddress]); } //@notice Returns how much a user has bet on the match. function ledgerUserBetContribution(address userAddress) public view returns (uint, uint) { return (teams[0].ledgerBettingContribution[userAddress], teams[1].ledgerBettingContribution[userAddress]); } //@notice Private function the helps in comparing strings. function compareStrings(string a, string b) private pure returns (bool){ return keccak256(a) == keccak256(b); } } contract MatchBettingFactory is Ownable { // Array of all the matches deployed address[] deployedMatches; // The address to which some ether is to be transferred address public jackpotAddress; //@notice Constructor thats sets up the jackpot address function MatchBettingFactory(address _jackpotAddress) public{ jackpotAddress = _jackpotAddress; } //@notice Creates a match with given team names, minimum bet amount and a match number function createMatch(string teamA, string teamB, uint _minimumBetAmount, uint _matchNumber) public onlyOwner{ address matchBetting = new MatchBetting(teamA, teamB, _minimumBetAmount, msg.sender, jackpotAddress, _matchNumber); deployedMatches.push(matchBetting); } //@notice get a address of all deployed matches function getDeployedMatches() public view returns (address[]) { return deployedMatches; } }
TOD1
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract EternalStorage is Ownable { struct Storage { mapping(uint256 => uint256) _uint; mapping(uint256 => address) _address; } Storage internal s; address allowed; constructor(uint _rF, address _r, address _f, address _a, address _t) public { setAddress(0, _a); setAddress(1, _r); setUint(1, _rF); setAddress(2, _f); setAddress(3, _t); } modifier onlyAllowed() { require(msg.sender == owner || msg.sender == allowed); _; } function identify(address _address) external onlyOwner { allowed = _address; } /** * @dev Allows the current owner to transfer control of the contract to a * newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { Ownable.transferOwnership(newOwner); } /** * @dev Allows the owner to set a value for an unsigned integer variable. * @param i Unsigned integer variable key * @param v The value to be stored */ function setUint(uint256 i, uint256 v) public onlyOwner { s._uint[i] = v; } /** * @dev Allows the owner to set a value for a address variable. * @param i Unsigned integer variable key * @param v The value to be stored */ function setAddress(uint256 i, address v) public onlyOwner { s._address[i] = v; } /** * @dev Get the value stored of a uint variable by the hash name * @param i Unsigned integer variable key */ function getUint(uint256 i) external view onlyAllowed returns (uint256) { return s._uint[i]; } /** * @dev Get the value stored of a address variable by the hash name * @param i Unsigned integer variable key */ function getAddress(uint256 i) external view onlyAllowed returns (address) { return s._address[i]; } function selfDestruct () external onlyOwner { selfdestruct(owner); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Escrow is Ownable { enum transactionStatus { Default, Pending, PendingR1, PendingR2, Completed, Canceled} struct Transaction { transactionStatus status; uint baseAmt; uint txnAmt; uint sellerFee; uint buyerFee; uint buyerBalance; address buyer; uint token; } mapping(address => Transaction) transactions; mapping(address => uint) balance; ERC20 base; ERC20 token; EternalStorage eternal; uint rF; address r; address reserve; constructor(ERC20 _base, address _s) public { base = _base; eternal = EternalStorage(_s); } modifier onlyAllowed() { require(msg.sender == owner || msg.sender == eternal.getAddress(0)); _; } function createTransaction ( address _tag, uint _baseAmt, uint _txnAmt, uint _sellerFee, uint _buyerFee) external payable { Transaction storage transaction = transactions[_tag]; require(transaction.buyer == 0x0); transactions[_tag] = Transaction( transactionStatus.Pending, _baseAmt, _txnAmt, _sellerFee, _buyerFee, 0, msg.sender, 0); uint buyerTotal = _txnAmt + _buyerFee; require(transaction.buyerBalance + msg.value == buyerTotal); transaction.buyerBalance += msg.value; balance[msg.sender] += msg.value; } function createTokenTransaction ( address _tag, uint _baseAmt, uint _txnAmt, uint _sellerFee, uint _buyerFee, address _buyer, uint _token) external onlyAllowed { require(_token != 0); require(eternal.getAddress(_token) != 0x0); Transaction storage transaction = transactions[_tag]; require(transaction.buyer == 0x0); transactions[_tag] = Transaction( transactionStatus.Pending, _baseAmt, _txnAmt, _sellerFee, _buyerFee, 0, _buyer, _token); uint buyerTotal = _txnAmt + _buyerFee; token = ERC20(eternal.getAddress(_token)); token.transferFrom(_buyer, address(this), buyerTotal); transaction.buyerBalance += buyerTotal; } function release(address _tag) external onlyAllowed { releaseFunds(_tag); } function releaseFunds (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.Pending); uint buyerTotal = transaction.txnAmt + transaction.buyerFee; uint buyerBalance = transaction.buyerBalance; transaction.buyerBalance = 0; require(buyerTotal == buyerBalance); base.transferFrom(_tag, transaction.buyer, transaction.baseAmt); uint totalFees = transaction.buyerFee + transaction.sellerFee; uint sellerTotal = transaction.txnAmt - transaction.sellerFee; transaction.txnAmt = 0; transaction.sellerFee = 0; if (transaction.token == 0) { _tag.transfer(sellerTotal); owner.transfer(totalFees); } else { token = ERC20(eternal.getAddress(transaction.token)); token.transfer(_tag, sellerTotal); token.transfer(owner, totalFees); } transaction.status = transactionStatus.PendingR1; recovery(_tag); } function recovery(address _tag) private { r1(_tag); r2(_tag); } function r1 (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.PendingR1); transaction.status = transactionStatus.PendingR2; base.transferFrom(reserve, _tag, rF); } function r2 (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.PendingR2); transaction.buyer = 0x0; transaction.status = transactionStatus.Completed; base.transferFrom(_tag, r, rF); } function cancel (address _tag) external onlyAllowed { Transaction storage transaction = transactions[_tag]; if (transaction.token == 0) { cancelTransaction(_tag); } else { cancelTokenTransaction(_tag); } } function cancelTransaction (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.Pending); uint refund = transaction.buyerBalance; transaction.buyerBalance = 0; address buyer = transaction.buyer; transaction.buyer = 0x0; buyer.transfer(refund); transaction.status = transactionStatus.Canceled; } function cancelTokenTransaction (address _tag) private { Transaction storage transaction = transactions[_tag]; require(transaction.status == transactionStatus.Pending); token = ERC20(eternal.getAddress(transaction.token)); uint refund = transaction.buyerBalance; transaction.buyerBalance = 0; address buyer = transaction.buyer; transaction.buyer = 0x0; token.transfer(buyer, refund); transaction.status = transactionStatus.Canceled; } function resync () external onlyOwner { rF = eternal.getUint(1); r = eternal.getAddress(1); reserve = eternal.getAddress(2); } function selfDestruct () external onlyOwner { selfdestruct(owner); } function status (address _tag) external view onlyOwner returns ( transactionStatus _status, uint _baseAmt, uint _txnAmt, uint _sellerFee, uint _buyerFee, uint _buyerBalance, address _buyer, uint _token) { Transaction storage transaction = transactions[_tag]; return ( transaction.status, transaction.baseAmt, transaction.txnAmt, transaction.sellerFee, transaction.buyerFee, transaction.buyerBalance, transaction.buyer, transaction.token ); } function getAddress (uint i) external view onlyAllowed returns (address) { return eternal.getAddress(i); } function variables () external view onlyAllowed returns ( address, address, address, uint) { address p = eternal.getAddress(0); return (p, r, reserve, rF); } }
TOD1
pragma solidity ^0.4.23; contract Necropolis { function addDragon(address _lastDragonOwner, uint256 _dragonID, uint256 _deathReason) external; } contract GenRNG { function getNewGens(address _from, uint256 _dragonID) external returns (uint256[2] resultGen); } contract DragonSelectFight2Death { function addSelctFight2Death( address _dragonOwner, uint256 _yourDragonID, uint256 _oppDragonID, uint256 _endBlockNumber, uint256 _priceSelectFight2Death ) external; } contract DragonsRandomFight2Death { function addRandomFight2Death(address _dragonOwner, uint256 _DragonID) external; } contract FixMarketPlace { function add2MarketPlace(address _dragonOwner, uint256 _dragonID, uint256 _dragonPrice, uint256 _endBlockNumber) external returns (bool); } contract Auction { function add2Auction( address _dragonOwner, uint256 _dragonID, uint256 _startPrice, uint256 _step, uint256 _endPrice, uint256 _endBlockNumber ) external returns (bool); } contract DragonStats { function setParents(uint256 _dragonID, uint256 _parentOne, uint256 _parentTwo) external; function setBirthBlock(uint256 _dragonID) external; function incChildren(uint256 _dragonID) external; function setDeathBlock(uint256 _dragonID) external; function getDragonFight(uint256 _dragonID) external view returns (uint256); } contract SuperContract { function checkDragon(uint256 _dragonID) external returns (bool); } contract Mutagen2Face { function addDragon(address _dragonOwner, uint256 _dragonID, uint256 mutagenCount) external; } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } contract RBACWithAdmin is RBAC { /** * A constant role name for indicating admins. */ string public constant ROLE_ADMIN = "admin"; string public constant ROLE_PAUSE_ADMIN = "pauseAdmin"; /** * @dev modifier to scope access to admins * // reverts */ modifier onlyAdmin() { checkRole(msg.sender, ROLE_ADMIN); _; } modifier onlyPauseAdmin() { checkRole(msg.sender, ROLE_PAUSE_ADMIN); _; } /** * @dev constructor. Sets msg.sender as admin by default */ constructor() public { addRole(msg.sender, ROLE_ADMIN); addRole(msg.sender, ROLE_PAUSE_ADMIN); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function adminAddRole(address addr, string roleName) onlyAdmin public { addRole(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function adminRemoveRole(address addr, string roleName) onlyAdmin public { removeRole(addr, roleName); } } contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public payable; 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 payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public payable; } contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) external view returns (string); } contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @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]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner 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 Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev 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 payable{ address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; if (msg.value > 0 && _to != address(0)) _to.transfer(msg.value); if (msg.value > 0 && _to == address(0)) owner.transfer(msg.value); emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev 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 * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev 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 payable canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); if (msg.value > 0) _to.transfer(msg.value); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev 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,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev 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 payable canTransfer(_tokenId) { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev 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,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev 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 _data ) public payable canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @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) public view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev 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 by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev 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 whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs // mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ bytes constant firstPartURI = "https://www.dragonseth.com/image/"; function tokenURI(uint256 _tokenId) external view returns (string) { require(exists(_tokenId)); bytes memory tmpBytes = new bytes(96); uint256 i = 0; uint256 tokenId = _tokenId; // for same use case need "if (tokenId == 0)" while (tokenId != 0) { uint256 remainderDiv = tokenId % 10; tokenId = tokenId / 10; tmpBytes[i++] = byte(48 + remainderDiv); } bytes memory resaultBytes = new bytes(firstPartURI.length + i); for (uint256 j = 0; j < firstPartURI.length; j++) { resaultBytes[j] = firstPartURI[j]; } i--; for (j = 0; j <= i; j++) { resaultBytes[j + firstPartURI.length] = tmpBytes[i - j]; } return string(resaultBytes); } /* function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } */ /** * @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 totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev 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 < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev 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 _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } */ /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev 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 by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @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]; } */ // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) external view returns (uint256[]) { return ownedTokens[_owner]; } } contract DragonsETH_GC is RBACWithAdmin { GenRNG public genRNGContractAddress; FixMarketPlace public fmpContractAddress; DragonStats public dragonsStatsContract; Necropolis public necropolisContract; Auction public auctionContract; SuperContract public superContract; DragonSelectFight2Death public selectFight2DeathContract; DragonsRandomFight2Death public randomFight2DeathContract; Mutagen2Face public mutagen2FaceContract; address wallet; uint8 adultDragonStage = 3; bool stageThirdBegin = false; uint256 constant UINT256_MAX = 115792089237316195423570985008687907853269984665640564039457584007913129639935; uint256 public secondsInBlock = 15; uint256 public priceDecraseTime2Action = 0.000005 ether; // 1 block uint256 public priceRandomFight2Death = 0.02 ether; uint256 public priceSelectFight2Death = 0.03 ether; uint256 public priceChangeName = 0.01 ether; uint256 public needFightToAdult = 100; function changeGenRNGcontractAddress(address _genRNGContractAddress) external onlyAdmin { genRNGContractAddress = GenRNG(_genRNGContractAddress); } function changeFMPcontractAddress(address _fmpContractAddress) external onlyAdmin { fmpContractAddress = FixMarketPlace(_fmpContractAddress); } function changeDragonsStatsContract(address _dragonsStatsContract) external onlyAdmin { dragonsStatsContract = DragonStats(_dragonsStatsContract); } function changeAuctionContract(address _auctionContract) external onlyAdmin { auctionContract = Auction(_auctionContract); } function changeSelectFight2DeathContract(address _selectFight2DeathContract) external onlyAdmin { selectFight2DeathContract = DragonSelectFight2Death(_selectFight2DeathContract); } function changeRandomFight2DeathContract(address _randomFight2DeathContract) external onlyAdmin { randomFight2DeathContract = DragonsRandomFight2Death(_randomFight2DeathContract); } function changeMutagen2FaceContract(address _mutagen2FaceContract) external onlyAdmin { mutagen2FaceContract = Mutagen2Face(_mutagen2FaceContract); } function changeSuperContract(address _superContract) external onlyAdmin { superContract = SuperContract(_superContract); } function changeWallet(address _wallet) external onlyAdmin { wallet = _wallet; } function changePriceDecraseTime2Action(uint256 _priceDecraseTime2Action) external onlyAdmin { priceDecraseTime2Action = _priceDecraseTime2Action; } function changePriceRandomFight2Death(uint256 _priceRandomFight2Death) external onlyAdmin { priceRandomFight2Death = _priceRandomFight2Death; } function changePriceSelectFight2Death(uint256 _priceSelectFight2Death) external onlyAdmin { priceSelectFight2Death = _priceSelectFight2Death; } function changePriceChangeName(uint256 _priceChangeName) external onlyAdmin { priceChangeName = _priceChangeName; } function changeSecondsInBlock(uint256 _secondsInBlock) external onlyAdmin { secondsInBlock = _secondsInBlock; } function changeNeedFightToAdult(uint256 _needFightToAdult) external onlyAdmin { needFightToAdult = _needFightToAdult; } function changeAdultDragonStage(uint8 _adultDragonStage) external onlyAdmin { adultDragonStage = _adultDragonStage; } function setStageThirdBegin() external onlyAdmin { stageThirdBegin = true; } function withdrawAllEther() external onlyAdmin { require(wallet != 0); wallet.transfer(address(this).balance); } // EIP-165 and EIP-721 bytes4 constant ERC165_Signature = 0x01ffc9a7; bytes4 constant ERC721_Signature = 0x80ac58cd; bytes4 constant ERC721Metadata_Signature = 0x5b5e139f; bytes4 constant ERC721Enumerable_Signature = 0x780e9d63; function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return ( (_interfaceID == ERC165_Signature) || (_interfaceID == ERC721_Signature) || (_interfaceID == ERC721Metadata_Signature) || (_interfaceID == ERC721Enumerable_Signature) ); } } contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } contract DragonsETH is ERC721Token("DragonsETH.com Dragon", "DragonsETH"), DragonsETH_GC, ReentrancyGuard { uint256 public totalDragons; uint256 public liveDragons; struct Dragon { uint256 gen1; uint8 stage; // 0 - Dead, 1 - Egg, 2 - Young Dragon ... uint8 currentAction; // 0 - free, 1 - fight place, 2 - random fight, 3 - breed market, 4 - breed auction, 5 - random breed ... 0xFF - Necropolis uint240 gen2; uint256 nextBlock2Action; } Dragon[] public dragons; mapping(uint256 => string) public dragonName; constructor(address _wallet, address _necropolisContract, address _dragonsStatsContract) public { _mint(msg.sender, 0); Dragon memory _dragon = Dragon({ gen1: 0, stage: 0, currentAction: 0, gen2: 0, nextBlock2Action: UINT256_MAX }); dragons.push(_dragon); transferFrom(msg.sender, _necropolisContract, 0); dragonsStatsContract = DragonStats(_dragonsStatsContract); necropolisContract = Necropolis(_necropolisContract); wallet = _wallet; } function add2MarketPlace(uint256 _dragonID, uint256 _dragonPrice, uint256 _endBlockNumber) external canTransfer(_dragonID) { require(dragons[_dragonID].stage != 0); // dragon not dead if (dragons[_dragonID].stage >= 2) { checkDragonStatus(_dragonID, 2); } address dragonOwner = ownerOf(_dragonID); if (fmpContractAddress.add2MarketPlace(dragonOwner, _dragonID, _dragonPrice, _endBlockNumber)) { transferFrom(dragonOwner, fmpContractAddress, _dragonID); } } function add2Auction( uint256 _dragonID, uint256 _startPrice, uint256 _step, uint256 _endPrice, uint256 _endBlockNumber ) external canTransfer(_dragonID) { require(dragons[_dragonID].stage != 0); // dragon not dead if (dragons[_dragonID].stage >= 2) { checkDragonStatus(_dragonID, 2); } address dragonOwner = ownerOf(_dragonID); if (auctionContract.add2Auction(dragonOwner, _dragonID, _startPrice, _step, _endPrice, _endBlockNumber)) { transferFrom(dragonOwner, auctionContract, _dragonID); } } function addRandomFight2Death(uint256 _dragonID) external payable nonReentrant canTransfer(_dragonID) { checkDragonStatus(_dragonID, adultDragonStage); if (priceRandomFight2Death > 0) { require(msg.value >= priceRandomFight2Death); wallet.transfer(priceRandomFight2Death); if (msg.value - priceRandomFight2Death > 0) msg.sender.transfer(msg.value - priceRandomFight2Death); } else { if (msg.value > 0) msg.sender.transfer(msg.value); } address dragonOwner = ownerOf(_dragonID); transferFrom(dragonOwner, randomFight2DeathContract, _dragonID); randomFight2DeathContract.addRandomFight2Death(dragonOwner, _dragonID); } function addSelctFight2Death(uint256 _yourDragonID, uint256 _oppDragonID, uint256 _endBlockNumber) external payable nonReentrant canTransfer(_yourDragonID) { checkDragonStatus(_yourDragonID, adultDragonStage); if (priceSelectFight2Death > 0) { require(msg.value >= priceSelectFight2Death); address(selectFight2DeathContract).transfer(priceSelectFight2Death); if (msg.value - priceSelectFight2Death > 0) msg.sender.transfer(msg.value - priceSelectFight2Death); } else { if (msg.value > 0) msg.sender.transfer(msg.value); } address dragonOwner = ownerOf(_yourDragonID); transferFrom(dragonOwner, selectFight2DeathContract, _yourDragonID); selectFight2DeathContract.addSelctFight2Death(dragonOwner, _yourDragonID, _oppDragonID, _endBlockNumber, priceSelectFight2Death); } function mutagen2Face(uint256 _dragonID, uint256 _mutagenCount) external canTransfer(_dragonID) { checkDragonStatus(_dragonID, 2); address dragonOwner = ownerOf(_dragonID); transferFrom(dragonOwner, mutagen2FaceContract, _dragonID); mutagen2FaceContract.addDragon(dragonOwner, _dragonID, _mutagenCount); } function createDragon( address _to, uint256 _timeToBorn, uint256 _parentOne, uint256 _parentTwo, uint256 _gen1, uint240 _gen2 ) external onlyRole("CreateContract") { totalDragons++; liveDragons++; _mint(_to, totalDragons); uint256[2] memory twoGen; if (_parentOne == 0 && _parentTwo == 0 && _gen1 == 0 && _gen2 == 0) { twoGen = genRNGContractAddress.getNewGens(_to, totalDragons); } else { twoGen[0] = _gen1; twoGen[1] = uint256(_gen2); } Dragon memory _dragon = Dragon({ gen1: twoGen[0], stage: 1, currentAction: 0, gen2: uint240(twoGen[1]), nextBlock2Action: _timeToBorn }); dragons.push(_dragon); if (_parentOne != 0) { dragonsStatsContract.setParents(totalDragons,_parentOne,_parentTwo); dragonsStatsContract.incChildren(_parentOne); dragonsStatsContract.incChildren(_parentTwo); } dragonsStatsContract.setBirthBlock(totalDragons); } function changeDragonGen(uint256 _dragonID, uint256 _gen, uint8 _which) external onlyRole("ChangeContract") { require(dragons[_dragonID].stage >= 2); // dragon not dead and not egg if (_which == 0) { dragons[_dragonID].gen1 = _gen; } else { dragons[_dragonID].gen2 = uint240(_gen); } } function birthDragon(uint256 _dragonID) external canTransfer(_dragonID) { require(dragons[_dragonID].stage != 0); // dragon not dead require(dragons[_dragonID].nextBlock2Action <= block.number); dragons[_dragonID].stage = 2; } function matureDragon(uint256 _dragonID) external canTransfer(_dragonID) { require(stageThirdBegin); checkDragonStatus(_dragonID, 2); require(dragonsStatsContract.getDragonFight(_dragonID) >= needFightToAdult); dragons[_dragonID].stage = 3; } function superDragon(uint256 _dragonID) external canTransfer(_dragonID) { checkDragonStatus(_dragonID, 3); require(superContract.checkDragon(_dragonID)); dragons[_dragonID].stage = 4; } function killDragon(uint256 _dragonID) external onlyOwnerOf(_dragonID) { checkDragonStatus(_dragonID, 2); dragons[_dragonID].stage = 0; dragons[_dragonID].currentAction = 0xFF; dragons[_dragonID].nextBlock2Action = UINT256_MAX; necropolisContract.addDragon(ownerOf(_dragonID), _dragonID, 1); transferFrom(ownerOf(_dragonID), necropolisContract, _dragonID); dragonsStatsContract.setDeathBlock(_dragonID); liveDragons--; } function killDragonDeathContract(address _lastOwner, uint256 _dragonID, uint256 _deathReason) external canTransfer(_dragonID) onlyRole("DeathContract") { checkDragonStatus(_dragonID, 2); dragons[_dragonID].stage = 0; dragons[_dragonID].currentAction = 0xFF; dragons[_dragonID].nextBlock2Action = UINT256_MAX; necropolisContract.addDragon(_lastOwner, _dragonID, _deathReason); transferFrom(ownerOf(_dragonID), necropolisContract, _dragonID); dragonsStatsContract.setDeathBlock(_dragonID); liveDragons--; } function decraseTimeToAction(uint256 _dragonID) external payable nonReentrant canTransfer(_dragonID) { require(dragons[_dragonID].stage != 0); // dragon not dead require(msg.value >= priceDecraseTime2Action); require(dragons[_dragonID].nextBlock2Action > block.number); uint256 maxBlockCount = dragons[_dragonID].nextBlock2Action - block.number; if (msg.value > maxBlockCount * priceDecraseTime2Action) { msg.sender.transfer(msg.value - maxBlockCount * priceDecraseTime2Action); wallet.transfer(maxBlockCount * priceDecraseTime2Action); dragons[_dragonID].nextBlock2Action = 0; } else { if (priceDecraseTime2Action == 0) { dragons[_dragonID].nextBlock2Action = 0; } else { wallet.transfer(msg.value); dragons[_dragonID].nextBlock2Action = dragons[_dragonID].nextBlock2Action - msg.value / priceDecraseTime2Action - 1; } } } function addDragonName(uint256 _dragonID,string _newName) external payable nonReentrant canTransfer(_dragonID) { checkDragonStatus(_dragonID, 2); if (bytes(dragonName[_dragonID]).length == 0) { dragonName[_dragonID] = _newName; if (msg.value > 0) msg.sender.transfer(msg.value); } else { if (priceChangeName == 0) { dragonName[_dragonID] = _newName; if (msg.value > 0) msg.sender.transfer(msg.value); } else { require(msg.value >= priceChangeName); wallet.transfer(priceChangeName); if (msg.value - priceChangeName > 0) msg.sender.transfer(msg.value - priceChangeName); dragonName[_dragonID] = _newName; } } } function checkDragonStatus(uint256 _dragonID, uint8 _stage) public view { require(dragons[_dragonID].stage != 0); // dragon not dead // dragon not in action and not in rest and not egg require( dragons[_dragonID].nextBlock2Action <= block.number && dragons[_dragonID].currentAction == 0 && dragons[_dragonID].stage >= _stage ); } function setCurrentAction(uint256 _dragonID, uint8 _currentAction) external onlyRole("ActionContract") { dragons[_dragonID].currentAction = _currentAction; } function setTime2Rest(uint256 _dragonID, uint256 _addNextBlock2Action) external onlyRole("ActionContract") { dragons[_dragonID].nextBlock2Action = block.number + _addNextBlock2Action; } }
TOD1
pragma solidity ^0.4.20; contract YUOR_CHANCE { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function set_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.20; contract quiz_quest { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 3 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function set_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.18; /** * Bob's Repair Token * https://bobsrepair.com/ * Using Blockchain to eliminate review fraud and provide lower pricing in the home repair industry through a decentralized platform. */ //=== OpenZeppelin Library Contracts https://github.com/OpenZeppelin/zeppelin-solidity === /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 @param _spender The address that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) pure external { from_; value_; data_; revert(); } } /** * @title Base contract for contracts that should not own things. * @author Remco Bloemen <remco@2π.com> * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or * Owned contracts. See respective base contracts for details. */ contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } // === Modified OpenZeppelin contracts === /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). * Based on https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); return true; } } /** * @title BOBTokenVesting * @dev Extends TokenVesting contract to allow reclaim ether and contracts, if transfered to this by mistake. */ contract BOBTokenVesting is TokenVesting, HasNoEther, HasNoContracts, Destructible { /** * @dev Call consturctor of TokenVesting with exactly same parameters */ function BOBTokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) TokenVesting( _beneficiary, _start, _cliff, _duration, _revocable) public {} } /** * @title Pausable ERC827token * @dev ERC827Token modified with pausable transfers. Based on OpenZeppelin's PausableToken **/ contract PausableERC827Token is ERC827Token, Pausable { // ERC20 functions function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } //ERC827 functions function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused returns (bool) { return super.transfer(_to, _value, _data); } function transferFrom(address _from, address _to, uint256 _value, bytes _data) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value, _data); } function approve(address _spender, uint256 _value, bytes _data) public whenNotPaused returns (bool) { return super.approve(_spender, _value, _data); } function increaseApproval(address _spender, uint _addedValue, bytes _data) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue, _data); } function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue, _data); } } // === Bob's Repair Contracts === /** * @title Airdroppable Token */ contract AirdropToken is PausableERC827Token { using SafeMath for uint256; uint8 private constant PERCENT_DIVIDER = 100; event AirdropStart(uint256 multiplierPercent, uint256 airdropNumber); event AirdropComplete(uint256 airdropNumber); uint256 public multiplierPercent = 0; //Multiplier of current airdrop (for example, multiplierPercent = 200 and holder balance is 1 TOKEN, after airdrop it will be 2 TOKEN) uint256 public currentAirdrop = 0; //Number of current airdrop. If 0 - no airdrop started uint256 public undropped; //Amount not yet airdropped mapping(address => uint256) public airdropped; //map of alreday airdropped addresses /** * @notice Start airdrop * @param _multiplierPercent Multiplier of the airdrop */ function startAirdrop(uint256 _multiplierPercent) onlyOwner external returns(bool){ pause(); require(multiplierPercent == 0); //This means airdrop was finished require(_multiplierPercent > PERCENT_DIVIDER); //Require that after airdrop amount of tokens will be greater than before currentAirdrop = currentAirdrop.add(1); multiplierPercent = _multiplierPercent; undropped = totalSupply(); assert(multiplierPercent.mul(undropped) > 0); //Assert that wrong multiplier will not result in owerflow in airdropAmount() AirdropStart(multiplierPercent, currentAirdrop); } /** * @notice Finish airdrop, unpause token transfers * @dev Anyone can call this function after all addresses are airdropped */ function finishAirdrop() external returns(bool){ require(undropped == 0); multiplierPercent = 0; AirdropComplete(currentAirdrop); unpause(); } /** * @notice Execute airdrop for a bunch of addresses. Should be repeated for all addresses with non-zero amount of tokens. * @dev This function can be called by anyone, not only the owner * @param holders Array of token holder addresses. * @return true if success */ function drop(address[] holders) external returns(bool){ for(uint256 i=0; i < holders.length; i++){ address holder = holders[i]; if(!isAirdropped(holder)){ uint256 balance = balances[holder]; undropped = undropped.sub(balance); balances[holder] = airdropAmount(balance); uint256 amount = balances[holder].sub(balance); totalSupply_ = totalSupply_.add(amount); Transfer(address(0), holder, amount); setAirdropped(holder); } } } /** * @notice Calculates amount of tokens after airdrop * @param amount Balance before airdrop * @return Amount of tokens after airdrop */ function airdropAmount(uint256 amount) view public returns(uint256){ require(multiplierPercent > 0); return multiplierPercent.mul(amount).div(PERCENT_DIVIDER); } /** * @dev Check if address was already airdropped * @param holder Address of token holder * @return true if address was airdropped */ function isAirdropped(address holder) view internal returns(bool){ return (airdropped[holder] == currentAirdrop); } /** * @dev Mark address as airdropped * @param holder Address of token holder */ function setAirdropped(address holder) internal { airdropped[holder] = currentAirdrop; } } contract BOBToken is AirdropToken, MintableToken, BurnableToken, NoOwner { string public symbol = 'BOB'; string public name = 'BOB Token'; uint8 public constant decimals = 18; address founder; //founder address to allow him transfer tokens even when transfers disabled bool public transferEnabled; //allows to dissable transfers while minting and in case of emergency function setFounder(address _founder) onlyOwner public { founder = _founder; } function setTransferEnabled(bool enable) onlyOwner public { transferEnabled = enable; } /** * Allow transfer only after crowdsale finished */ modifier canTransfer() { require( transferEnabled || msg.sender == founder || msg.sender == owner); _; } function transfer(address _to, uint256 _value) canTransfer public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns (bool) { return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value, bytes _data) canTransfer public returns (bool) { return super.transfer(_to, _value, _data); } function transferFrom(address _from, address _to, uint256 _value, bytes _data) canTransfer public returns (bool) { return super.transferFrom(_from, _to, _value, _data); } }
TOD1
pragma solidity ^0.4.13; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract PausableToken is Ownable { function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); function increaseFrozen(address _owner,uint256 _incrementalAmount) public returns (bool); function burn(uint256 _value) public; } contract AddressWhitelist is Ownable { // the addresses that are included in the whitelist mapping (address => bool) whitelisted; function isWhitelisted(address addr) view public returns (bool) { return whitelisted[addr]; } event LogWhitelistAdd(address indexed addr); // add these addresses to the whitelist function addToWhitelist(address[] addresses) public onlyOwner returns (bool) { for (uint i = 0; i < addresses.length; i++) { if (!whitelisted[addresses[i]]) { whitelisted[addresses[i]] = true; LogWhitelistAdd(addresses[i]); } } return true; } event LogWhitelistRemove(address indexed addr); // remove these addresses from the whitelist function removeFromWhitelist(address[] addresses) public onlyOwner returns (bool) { for (uint i = 0; i < addresses.length; i++) { if (whitelisted[addresses[i]]) { whitelisted[addresses[i]] = false; LogWhitelistRemove(addresses[i]); } } return true; } } contract RtcTokenCrowdsale is Ownable, AddressWhitelist { using SafeMath for uint256; PausableToken public tokenReward; // address of the token used as reward // deployment variables for static supply sale uint256 public initialSupply; uint256 public tokensRemaining; uint256 public decimals; // multi-sig addresses and price variable address public beneficiaryWallet; // beneficiaryMultiSig (founder group) or wallet account uint256 public tokensPerEthPrice; // set initial value floating priceVar 10,000 tokens per Eth // uint256 values for min,max,caps,tracking uint256 public amountRaisedInWei; uint256 public fundingMinCapInWei; // pricing veriable uint256 public p1_duration; uint256 public p1_start; uint256 public p2_start; uint256 public white_duration; // loop control, ICO startup and limiters uint256 public fundingStartTime; // crowdsale start time# uint256 public fundingEndTime; // crowdsale end time# bool public isCrowdSaleClosed = false; // crowdsale completion boolean bool public areFundsReleasedToBeneficiary = false; // boolean for founder to receive Eth or not bool public isCrowdSaleSetup = false; // boolean for crowdsale setup // Gas price limit uint256 maxGasPrice = 50000000000; event Buy(address indexed _sender, uint256 _eth, uint256 _RTC); event Refund(address indexed _refunder, uint256 _value); mapping(address => uint256) fundValue; // convert tokens to decimals function toSmallrtc(uint256 amount) public constant returns (uint256) { return amount.mul(10**decimals); } // convert tokens to whole function toRtc(uint256 amount) public constant returns (uint256) { return amount.div(10**decimals); } function updateMaxGasPrice(uint256 _newGasPrice) public onlyOwner { require(_newGasPrice != 0); maxGasPrice = _newGasPrice; } // setup the CrowdSale parameters function setupCrowdsale(uint256 _fundingStartTime) external onlyOwner { if ((!(isCrowdSaleSetup)) && (!(beneficiaryWallet > 0))){ // init addresses tokenReward = PausableToken(0xC9906549d5F31b6C6A920441e4c2C33EedCe97AB); beneficiaryWallet = 0xd57fC702773698B9F84D6eaDaDe9E38E67Fe1C2E; tokensPerEthPrice = 10000; // 1 ETH = 10,000 RTC // funding targets fundingMinCapInWei = 350; //350 (min cap) (test = 15) - crowdsale is considered success after this value // update values decimals = 18; amountRaisedInWei = 0; initialSupply = toSmallrtc(35000000); // 35 million * 18 decimal tokensRemaining = initialSupply; fundingStartTime = _fundingStartTime; white_duration = 2 weeks; // 2 week (test = 2 hour) p1_duration = 4 weeks; // 4 week (test = 2 hour) p1_start = fundingStartTime + white_duration; p2_start = p1_start + p1_duration + 4 weeks; // + 4 week after p1 ends (test = 4 hour) fundingEndTime = p2_start + 4 weeks; // + 4 week (test = 4 hour) // configure crowdsale isCrowdSaleSetup = true; isCrowdSaleClosed = false; } } function setBonusPrice() public constant returns (uint256 bonus) { require(isCrowdSaleSetup); require(p1_start + p1_duration <= p2_start); if (now >= fundingStartTime && now <= p1_start) { // Private sale Bonus 40% = 4,000 RTC = 1 ETH bonus = 4000; } else if (now > p1_start && now <= p1_start + p1_duration) { // Phase-1 Bonus 30% = 3,000 RTC = 1 ETH bonus = 3000; } else if (now > p2_start && now <= p2_start + 1 days ) { // Phase-2 1st day Bonus 25% = 2,500 RTC = 1 ETH bonus = 2500; } else if (now > p2_start + 1 days && now <= p2_start + 1 weeks ) { // Phase-2 week-1 Bonus 20% = 2,000 RTC = 1 ETH bonus = 2000; } else if (now > p2_start + 1 weeks && now <= p2_start + 2 weeks ) { // Phase-2 week-2 Bonus +15% = 1,500 RTC = 1 ETH bonus = 1500; } else if (now > p2_start + 2 weeks && now <= p2_start + 3 weeks ) { // Phase-2 week-3 Bonus +10% = 1,000 RTC = 1 ETH bonus = 1000; } else if (now > p2_start + 3 weeks && now <= fundingEndTime ) { // Phase-2 final week Bonus 5% = 500 RTC = 1 ETH bonus = 500; } else { revert(); } } // p1_duration constant. Only p2 start changes. p2 start cannot be greater than 1 month from p1 end function updateDuration(uint256 _newP2Start) external onlyOwner { // function to update the duration of phase-1 and adjust the start time of phase-2 require(isCrowdSaleSetup && !(p2_start == _newP2Start) && !(_newP2Start > p1_start + p1_duration + 30 days) && (now < p2_start) && (fundingStartTime + p1_duration < _newP2Start)); p2_start = _newP2Start; fundingEndTime = p2_start.add(4 weeks); // 4 week } // default payable function when sending ether to this contract function () external payable { require(tx.gasprice <= maxGasPrice); require(msg.data.length == 0); BuyRTCtokens(); } function BuyRTCtokens() public payable { // conditions (length, crowdsale setup, zero check, exceed funding contrib check, contract valid check, within funding block range check, balance overflow check etc) require(!(msg.value == 0) && (isCrowdSaleSetup) && (now >= fundingStartTime) && (now <= fundingEndTime) && (tokensRemaining > 0)); // only whitelisted addresses are allowed during the first day of phase 1 if (now <= p1_start) { assert(isWhitelisted(msg.sender)); } uint256 rewardTransferAmount = 0; uint256 rewardBaseTransferAmount = 0; uint256 rewardBonusTransferAmount = 0; uint256 contributionInWei = msg.value; uint256 refundInWei = 0; rewardBonusTransferAmount = setBonusPrice(); rewardBaseTransferAmount = (msg.value.mul(tokensPerEthPrice)); // Since both ether and RTC have 18 decimals, No need of conversion rewardBonusTransferAmount = (msg.value.mul(rewardBonusTransferAmount)); // Since both ether and RTC have 18 decimals, No need of conversion rewardTransferAmount = rewardBaseTransferAmount.add(rewardBonusTransferAmount); if (rewardTransferAmount > tokensRemaining) { uint256 partialPercentage; partialPercentage = tokensRemaining.mul(10**18).div(rewardTransferAmount); contributionInWei = contributionInWei.mul(partialPercentage).div(10**18); rewardBonusTransferAmount = rewardBonusTransferAmount.mul(partialPercentage).div(10**18); rewardTransferAmount = tokensRemaining; refundInWei = msg.value.sub(contributionInWei); } amountRaisedInWei = amountRaisedInWei.add(contributionInWei); tokensRemaining = tokensRemaining.sub(rewardTransferAmount); // will cause throw if attempt to purchase over the token limit in one tx or at all once limit reached fundValue[msg.sender] = fundValue[msg.sender].add(contributionInWei); assert(tokenReward.increaseFrozen(msg.sender, rewardBonusTransferAmount)); tokenReward.transfer(msg.sender, rewardTransferAmount); Buy(msg.sender, contributionInWei, rewardTransferAmount); if (refundInWei > 0) { msg.sender.transfer(refundInWei); } } function beneficiaryMultiSigWithdraw() external onlyOwner { checkGoalReached(); require(areFundsReleasedToBeneficiary && (amountRaisedInWei >= fundingMinCapInWei)); beneficiaryWallet.transfer(this.balance); } function checkGoalReached() public returns (bytes32 response) { // return crowdfund status to owner for each result case, update public constant // update state & status variables require (isCrowdSaleSetup); if ((amountRaisedInWei < fundingMinCapInWei) && (block.timestamp <= fundingEndTime && block.timestamp >= fundingStartTime)) { // ICO in progress, under softcap areFundsReleasedToBeneficiary = false; isCrowdSaleClosed = false; return "In progress (Eth < Softcap)"; } else if ((amountRaisedInWei < fundingMinCapInWei) && (block.timestamp < fundingStartTime)) { // ICO has not started areFundsReleasedToBeneficiary = false; isCrowdSaleClosed = false; return "Crowdsale is setup"; } else if ((amountRaisedInWei < fundingMinCapInWei) && (block.timestamp > fundingEndTime)) { // ICO ended, under softcap areFundsReleasedToBeneficiary = false; isCrowdSaleClosed = true; return "Unsuccessful (Eth < Softcap)"; } else if ((amountRaisedInWei >= fundingMinCapInWei) && (tokensRemaining == 0)) { // ICO ended, all tokens gone areFundsReleasedToBeneficiary = true; isCrowdSaleClosed = true; return "Successful (RTC >= Hardcap)!"; } else if ((amountRaisedInWei >= fundingMinCapInWei) && (block.timestamp > fundingEndTime) && (tokensRemaining > 0)) { // ICO ended, over softcap! areFundsReleasedToBeneficiary = true; isCrowdSaleClosed = true; return "Successful (Eth >= Softcap)!"; } else if ((amountRaisedInWei >= fundingMinCapInWei) && (tokensRemaining > 0) && (block.timestamp <= fundingEndTime)) { // ICO in progress, over softcap! areFundsReleasedToBeneficiary = true; isCrowdSaleClosed = false; return "In progress (Eth >= Softcap)!"; } } function refund() external { // any contributor can call this to have their Eth returned. user's purchased RTC tokens are burned prior refund of Eth. checkGoalReached(); //require minCap not reached require ((amountRaisedInWei < fundingMinCapInWei) && (isCrowdSaleClosed) && (now > fundingEndTime) && (fundValue[msg.sender] > 0)); //refund Eth sent uint256 ethRefund = fundValue[msg.sender]; fundValue[msg.sender] = 0; //send Eth back, burn tokens msg.sender.transfer(ethRefund); Refund(msg.sender, ethRefund); } function burnRemainingTokens() onlyOwner external { require(now > fundingEndTime); uint256 tokensToBurn = tokenReward.balanceOf(this); tokenReward.burn(tokensToBurn); } } 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; } }
TOD1
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract OpportyToken is StandardToken { string public constant name = "OpportyToken"; string public constant symbol = "OPP"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); /** * @dev Contructor that gives msg.sender all of existing tokens. */ function OpportyToken() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract OpportyWhiteListHold is Ownable { using SafeMath for uint256; // Addresses and contracts OpportyToken public OppToken; struct Holder { bool isActive; uint tokens; uint8 holdPeriod; uint holdPeriodTimestamp; bool withdrawed; } mapping(address => Holder) public holderList; mapping(uint => address) private holderIndexes; mapping (uint => address) private assetOwners; mapping (address => uint) private assetOwnersIndex; uint public assetOwnersIndexes; uint private holderIndex; event TokensTransfered(address contributor , uint amount); event Hold(address sender, address contributor, uint amount, uint8 holdPeriod); event ChangeHold(address sender, address contributor, uint amount, uint8 holdPeriod); event TokenChanged(address newAddress); event ManualPriceChange(uint beforePrice, uint afterPrice); modifier onlyAssetsOwners() { require(assetOwnersIndex[msg.sender] > 0 || msg.sender == owner); _; } function getBalanceContract() view internal returns (uint) { return OppToken.balanceOf(this); } function setToken(address newToken) public onlyOwner { OppToken = OpportyToken(newToken); TokenChanged(newToken); } function changeHold(address holder, uint tokens, uint8 period, uint holdTimestamp, bool withdrawed ) public onlyAssetsOwners { if (holderList[holder].isActive == true) { holderList[holder].tokens = tokens; holderList[holder].holdPeriod = period; holderList[holder].holdPeriodTimestamp = holdTimestamp; holderList[holder].withdrawed = withdrawed; ChangeHold(msg.sender, holder, tokens, period); } } function addHolder(address holder, uint tokens, uint8 timed, uint timest) onlyAssetsOwners external { if (holderList[holder].isActive == false) { holderList[holder].isActive = true; holderList[holder].tokens = tokens; holderList[holder].holdPeriod = timed; holderList[holder].holdPeriodTimestamp = timest; holderIndexes[holderIndex] = holder; holderIndex++; } else { holderList[holder].tokens += tokens; holderList[holder].holdPeriod = timed; holderList[holder].holdPeriodTimestamp = timest; } Hold(msg.sender, holder, tokens, timed); } function getBalance() public constant returns (uint) { return OppToken.balanceOf(this); } function returnTokens(uint nTokens) public onlyOwner returns (bool) { require(nTokens <= getBalance()); OppToken.transfer(msg.sender, nTokens); TokensTransfered(msg.sender, nTokens); return true; } function unlockTokens() public returns (bool) { require(holderList[msg.sender].isActive); require(!holderList[msg.sender].withdrawed); require(now >= holderList[msg.sender].holdPeriodTimestamp); OppToken.transfer(msg.sender, holderList[msg.sender].tokens); holderList[msg.sender].withdrawed = true; TokensTransfered(msg.sender, holderList[msg.sender].tokens); return true; } function addAssetsOwner(address _owner) public onlyOwner { assetOwnersIndexes++; assetOwners[assetOwnersIndexes] = _owner; assetOwnersIndex[_owner] = assetOwnersIndexes; } function removeAssetsOwner(address _owner) public onlyOwner { uint index = assetOwnersIndex[_owner]; delete assetOwnersIndex[_owner]; delete assetOwners[index]; assetOwnersIndexes--; } function getAssetsOwners(uint _index) onlyOwner public constant returns (address) { return assetOwners[_index]; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract OpportyWhiteList is Pausable { using SafeMath for uint256; OpportyToken public token; OpportyWhiteListHold public holdContract; enum SaleState { NEW, SALE, ENDED } SaleState public state; uint public endDate; uint public endSaleDate; uint public minimalContribution; // address where funds are collected address private wallet; address private preSaleOld; // total ETH collected uint public ethRaised; uint private price; uint public tokenRaised; bool public tokensTransferredToHold; /* Events */ event SaleStarted(uint blockNumber); event SaleEnded(uint blockNumber); event FundTransfered(address contrib, uint amount); event WithdrawedEthToWallet(uint amount); event ManualChangeEndDate(uint beforeDate, uint afterDate); event TokensTransferedToHold(address hold, uint amount); event AddedToWhiteList(address inv, uint amount, uint8 holdPeriod, uint8 bonus); event AddedToHolder(address sender, uint tokenAmount, uint8 holdPeriod, uint holdTimestamp); event ManualPriceChange(uint beforePrice, uint afterPrice); event ChangeMinAmount(uint oldMinAmount, uint minAmount); event TokenChanged(address newAddress); struct WhitelistContributor { bool isActive; uint invAmount; uint8 holdPeriod; uint holdTimestamp; uint8 bonus; bool payed; } mapping(address => WhitelistContributor) public whiteList; mapping(uint => address) private whitelistIndexes; uint private whitelistIndex; mapping (uint => address) private assetOwners; mapping (address => uint) private assetOwnersIndex; uint public assetOwnersIndexes; modifier onlyAssetsOwners() { require(assetOwnersIndex[msg.sender] > 0); _; } /* constructor */ function OpportyWhiteList( address walletAddress, uint end, uint endSale, address holdCont) public { state = SaleState.NEW; endDate = end; endSaleDate = endSale; price = 0.0002 * 1 ether; wallet = walletAddress; minimalContribution = 0.3 * 1 ether; holdContract = OpportyWhiteListHold(holdCont); addAssetsOwner(msg.sender); } function setToken(address newToken) public onlyOwner { token = OpportyToken(newToken); TokenChanged(token); } function startPresale() public onlyOwner { state = SaleState.SALE; SaleStarted(block.number); } function endPresale() public onlyOwner { state = SaleState.ENDED; SaleEnded(block.number); } function addToWhitelist(address inv, uint amount, uint8 holdPeriod, uint8 bonus) public onlyAssetsOwners { require(state == SaleState.NEW || state == SaleState.SALE); require(holdPeriod >= 1); require(amount >= minimalContribution); if (whiteList[inv].isActive == false) { whiteList[inv].isActive = true; whiteList[inv].payed = false; whitelistIndexes[whitelistIndex] = inv; whitelistIndex++; } whiteList[inv].invAmount = amount; whiteList[inv].holdPeriod = holdPeriod; whiteList[inv].bonus = bonus; whiteList[inv].holdTimestamp = endSaleDate.add(whiteList[inv].holdPeriod * 30 days); AddedToWhiteList(inv, whiteList[inv].invAmount, whiteList[inv].holdPeriod, whiteList[inv].bonus); } function() whenNotPaused public payable { require(state == SaleState.SALE); require(msg.value >= minimalContribution); require(whiteList[msg.sender].isActive); if (now > endDate) { state = SaleState.ENDED; msg.sender.transfer(msg.value); return; } WhitelistContributor memory contrib = whiteList[msg.sender]; require(contrib.invAmount <= msg.value || contrib.payed); if (whiteList[msg.sender].payed == false) { whiteList[msg.sender].payed = true; } ethRaised += msg.value; uint tokenAmount = msg.value.div(price); tokenAmount += tokenAmount.mul(contrib.bonus).div(100); tokenAmount *= 10 ** 18; tokenRaised += tokenAmount; holdContract.addHolder(msg.sender, tokenAmount, contrib.holdPeriod, contrib.holdTimestamp); AddedToHolder(msg.sender, tokenAmount, contrib.holdPeriod, contrib.holdTimestamp); FundTransfered(msg.sender, msg.value); // forward the funds to the wallet forwardFunds(); } /** * send ether to the fund collection wallet * override to create custom fund forwarding mechanisms */ function forwardFunds() internal { wallet.transfer(msg.value); } function getBalanceContract() view internal returns (uint) { return token.balanceOf(this); } function sendTokensToHold() public onlyOwner { require(state == SaleState.ENDED); require(getBalanceContract() >= tokenRaised); if (token.transfer(holdContract, tokenRaised)) { tokensTransferredToHold = true; TokensTransferedToHold(holdContract, tokenRaised); } } function getTokensBack() public onlyOwner { require(state == SaleState.ENDED); require(tokensTransferredToHold == true); uint balance; balance = getBalanceContract() ; token.transfer(msg.sender, balance); } function withdrawEth() public { require(this.balance != 0); require(state == SaleState.ENDED); require(msg.sender == wallet); require(tokensTransferredToHold == true); uint bal = this.balance; wallet.transfer(bal); WithdrawedEthToWallet(bal); } function setPrice(uint newPrice) public onlyOwner { uint oldPrice = price; price = newPrice; ManualPriceChange(oldPrice, newPrice); } function setEndSaleDate(uint date) public onlyOwner { uint oldEndDate = endSaleDate; endSaleDate = date; ManualChangeEndDate(oldEndDate, date); } function setEndDate(uint date) public onlyOwner { uint oldEndDate = endDate; endDate = date; ManualChangeEndDate(oldEndDate, date); } function setMinimalContribution(uint minimumAmount) public onlyOwner { uint oldMinAmount = minimalContribution; minimalContribution = minimumAmount; ChangeMinAmount(oldMinAmount, minimalContribution); } function getTokenBalance() public constant returns (uint) { return token.balanceOf(this); } function getEthRaised() constant external returns (uint) { return ethRaised; } function addAssetsOwner(address _owner) public onlyOwner { assetOwnersIndexes++; assetOwners[assetOwnersIndexes] = _owner; assetOwnersIndex[_owner] = assetOwnersIndexes; } function removeAssetsOwner(address _owner) public onlyOwner { uint index = assetOwnersIndex[_owner]; delete assetOwnersIndex[_owner]; delete assetOwners[index]; assetOwnersIndexes--; } function getAssetsOwners(uint _index) onlyOwner public constant returns (address) { return assetOwners[_index]; } }
TOD1
pragma solidity ^0.4.24; /** Proxy contract to buy tokens on Zethr, * because we forgot to add the onTokenBuy event to Zethr. * So we're proxying Zethr buys through this contract so that our website * can properly track and display Zethr token buys. **/ contract ZethrProxy { ZethrInterface zethr = ZethrInterface(address(0xD48B633045af65fF636F3c6edd744748351E020D)); address owner = msg.sender; event onTokenPurchase( address indexed customerAddress, uint incomingEthereum, uint tokensMinted, address indexed referredBy ); function buyTokensWithProperEvent(address _referredBy, uint8 divChoice) public payable { // Query token balance before & after to see how much we bought uint balanceBefore = zethr.balanceOf(msg.sender); // Buy tokens with selected div rate zethr.buyAndTransfer.value(msg.value)(_referredBy, msg.sender, "", divChoice); // Query balance after uint balanceAfter = zethr.balanceOf(msg.sender); emit onTokenPurchase( msg.sender, msg.value, balanceAfter - balanceBefore, _referredBy ); } function () public payable { } // Yes there are tiny amounts of divs generated on buy, // but not enough to justify transferring to msg.sender - gas price makes it not worth it. function withdrawMicroDivs() public { require(msg.sender == owner); owner.transfer(address(this).balance); } } contract ZethrInterface { function buyAndTransfer(address _referredBy, address target, bytes _data, uint8 divChoice) public payable; function balanceOf(address _owner) view public returns(uint); }
TOD1
// File: contracts/ERC721.sol // eterart-contract // contracts/ERC721.sol pragma solidity ^0.4.24; /** * @title ERC-721 contract interface. */ contract ERC721 { // ERC20 compatible functions. function name() public constant returns (string); function symbol() public constant returns (string); function totalSupply() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint); // Functions that define ownership. function ownerOf(uint256 _tokenId) public constant returns (address); function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint); // Token metadata. function tokenMetadata(uint256 _tokenId) public constant returns (string); // Events. event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); } // File: contracts/EterArt.sol // eterart-contract // contracts/EterArt.sol pragma solidity ^0.4.24; /** * @title EterArt contract. */ contract EterArt is ERC721 { // Art structure for tokens ownership registry. struct Art { uint256 price; address owner; address newOwner; } struct Token { uint256[] items; mapping(uint256 => uint) lookup; } // Mapping from token ID to owner. mapping (address => Token) internal ownedTokens; // All minted tokens number (ERC-20 compatibility). uint256 public totalTokenSupply; // Token issuer address address public _issuer; // Tokens ownership registry. mapping (uint => Art) public registry; // Token metadata base URL. string public baseInfoUrl = "https://www.eterart.com/art/"; // Fee in percents uint public feePercent = 5; /** * @dev Constructor sets the `issuer` of the contract to the sender * account. */ constructor() public { _issuer = msg.sender; } /** * @return the address of the issuer. */ function issuer() public view returns(address) { return _issuer; } /** * @dev Reject all Ether from being sent here. (Hopefully, we can prevent user accidents.) */ function() external payable { require(msg.sender == address(this)); } /** * @dev Gets token name (ERC-20 compatibility). * @return string token name. */ function name() public constant returns (string) { return "EterArt"; } /** * @dev Gets token symbol (ERC-20 compatibility). * @return string token symbol. */ function symbol() public constant returns (string) { return "WAW"; } /** * @dev Gets token URL. * @param _tokenId uint256 ID of the token to get URL of. * @return string token URL. */ function tokenMetadata(uint256 _tokenId) public constant returns (string) { return strConcat(baseInfoUrl, strConcat("0x", uint2hexstr(_tokenId))); } /** * @dev Gets contract all minted tokens number. * @return uint256 contract all minted tokens number. */ function totalSupply() public constant returns (uint256) { return totalTokenSupply; } /** * @dev Gets tokens number of specified address. * @param _owner address to query tokens number of. * @return uint256 number of tokens owned by the specified address. */ function balanceOf(address _owner) public constant returns (uint balance) { balance = ownedTokens[_owner].items.length; } /** * @dev Gets token by index of specified address. * @param _owner address to query tokens number of. * @param _index uint256 index of the token to get. * @return uint256 token ID from specified address tokens list by specified index. */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint tokenId) { tokenId = ownedTokens[_owner].items[_index]; } /** * @dev Approve token ownership transfer to another address. * @param _to address to change token ownership to. * @param _tokenId uint256 token ID to change ownership of. */ function approve(address _to, uint256 _tokenId) public { require(_to != msg.sender); require(registry[_tokenId].owner == msg.sender); registry[_tokenId].newOwner = _to; emit Approval(registry[_tokenId].owner, _to, _tokenId); } /** * @dev Internal method that transfer token to another address. * Run some checks and internal contract data manipulations. * @param _to address new token owner address. * @param _tokenId uint256 token ID to transfer to specified address. */ function _transfer(address _to, uint256 _tokenId) internal { if (registry[_tokenId].owner != address(0)) { require(registry[_tokenId].owner != _to); removeByValue(registry[_tokenId].owner, _tokenId); } else { totalTokenSupply = totalTokenSupply + 1; } require(_to != address(0)); push(_to, _tokenId); emit Transfer(registry[_tokenId].owner, _to, _tokenId); registry[_tokenId].owner = _to; registry[_tokenId].newOwner = address(0); registry[_tokenId].price = 0; } /** * @dev Take ownership of specified token. * Only if current token owner approve that. * @param _tokenId uint256 token ID to take ownership of. */ function takeOwnership(uint256 _tokenId) public { require(registry[_tokenId].newOwner == msg.sender); _transfer(msg.sender, _tokenId); } /** * @dev Change baseInfoUrl contract property value. * @param url string new baseInfoUrl value. */ function changeBaseInfoUrl(string url) public { require(msg.sender == _issuer); baseInfoUrl = url; } /** * @dev Change issuer contract address. * @param _to address of new contract issuer. */ function changeIssuer(address _to) public { require(msg.sender == _issuer); _issuer = _to; } /** * @dev Withdraw all contract balance value to contract issuer. */ function withdraw() public { require(msg.sender == _issuer); withdraw(_issuer, address(this).balance); } /** * @dev Withdraw all contract balance value to specified address. * @param _to address to transfer value. */ function withdraw(address _to) public { require(msg.sender == _issuer); withdraw(_to, address(this).balance); } /** * @dev Withdraw specified wei number to address. * @param _to address to transfer value. * @param _value uint wei amount value. */ function withdraw(address _to, uint _value) public { require(msg.sender == _issuer); require(_value <= address(this).balance); _to.transfer(address(this).balance); } /** * @dev Gets specified token owner address. * @param token uint256 token ID. * @return address specified token owner address. */ function ownerOf(uint256 token) public constant returns (address owner) { owner = registry[token].owner; } /** * @dev Gets specified token price. * @param token uint256 token ID. * @return uint specified token price. */ function getPrice(uint token) public view returns (uint) { return registry[token].price; } /** * @dev Direct transfer specified token to another address. * @param _to address new token owner address. * @param _tokenId uint256 token ID to transfer to specified address. */ function transfer(address _to, uint256 _tokenId) public { require(registry[_tokenId].owner == msg.sender); _transfer(_to, _tokenId); } /** * @dev Change specified token price. * Used for: change token price, * withdraw token from sale (set token price to 0 (zero)) * and for put up token for sale (set token price > 0) * @param token uint token ID to change price of. * @param price uint new token price. */ function changePrice(uint token, uint price) public { require(registry[token].owner == msg.sender); registry[token].price = price; } /** * @dev Buy specified token if it's marked as for sale (token price > 0). * Run some checks, calculate fee and transfer token to msg.sender. * @param _tokenId uint token ID to buy. */ function buy(uint _tokenId) public payable { require(registry[_tokenId].price > 0); uint calcedFee = ((registry[_tokenId].price / 100) * feePercent); uint value = msg.value - calcedFee; require(registry[_tokenId].price <= value); registry[_tokenId].owner.transfer(value); _transfer(msg.sender, _tokenId); } /** * @dev Mint token. */ function mint(uint _tokenId, address _to) public { require(msg.sender == _issuer); require(registry[_tokenId].owner == 0x0); _transfer(_to, _tokenId); } /** * @dev Mint token. */ function mint( string length, uint _tokenId, uint price, uint8 v, bytes32 r, bytes32 s ) public payable { string memory m_price = uint2hexstr(price); string memory m_token = uint2hexstr(_tokenId); require(msg.value >= price); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n", length, m_token, m_price), v, r, s) == _issuer); require(registry[_tokenId].owner == 0x0); _transfer(msg.sender, _tokenId); } /** * UTILS */ /** * @dev Add token to specified address tokens list. * @param owner address address of token owner to add token to. * @param value uint token ID to add. */ function push(address owner, uint value) private { if (ownedTokens[owner].lookup[value] > 0) { return; } ownedTokens[owner].lookup[value] = ownedTokens[owner].items.push(value); } /** * @dev Remove token by ID from specified address tokens list. * @param owner address address of token owner to remove token from. * @param value uint token ID to remove. */ function removeByValue(address owner, uint value) private { uint index = ownedTokens[owner].lookup[value]; if (index == 0) { return; } if (index < ownedTokens[owner].items.length) { uint256 lastItem = ownedTokens[owner].items[ownedTokens[owner].items.length - 1]; ownedTokens[owner].items[index - 1] = lastItem; ownedTokens[owner].lookup[lastItem] = index; } ownedTokens[owner].items.length -= 1; delete ownedTokens[owner].lookup[value]; } /** * @dev String concatenation. * @param _a string first string. * @param _b string second string. * @return string result of string concatenation. */ function strConcat(string _a, string _b) internal pure returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory abcde = new string(_ba.length + _bb.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; return string(babcde); } /** * @dev Convert long to hex string. * @param i uint value to convert. * @return string specified value converted to hex string. */ function uint2hexstr(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint length; while (j != 0) { length++; j = j >> 4; } uint mask = 15; bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ uint curr = (i & mask); bstr[k--] = curr > 9 ? byte(55 + curr) : byte(48 + curr); // 55 = 65 - 10 i = i >> 4; } return string(bstr); } }
TOD1
pragma solidity ^0.4.18; /** * Math operations with safety checks */ contract SafeMath { function safeMult(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } } contract TokenERC20 { function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract BBBTESTToken is SafeMath, TokenERC20{ string public name = "BBBTEST"; string public symbol = "BBBTEST"; uint8 public decimals = 18; uint256 public totalSupply = 4204800; address public owner = 0x0; string public version = "1.0"; bool public locked = false; uint256 public currentSupply; uint256 public tokenRaised = 0; uint256 public tokenExchangeRate = 333; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; mapping (address => mapping (address => uint256)) public allowance; /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); /* IssueToken*/ event IssueToken(address indexed to, uint256 value); /* TransferOwnerEther*/ event TransferOwnerEther(address indexed to, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function BBBTESTToken( uint256 initialSupply, string tokenName, string tokenSymbol ) { totalSupply = formatDecimals(initialSupply); // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes currentSupply = totalSupply; symbol = tokenSymbol; // Set the symbol for display purposes owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier validAddress() { require(address(0) != msg.sender); _; } modifier unlocked() { require(!locked); _; } function formatDecimals(uint256 _value) internal returns (uint256 ) { return _value * 10 ** uint256(decimals); } function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOf[_owner]; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) validAddress unlocked returns (bool success) { require(_value > 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /*Function to check the amount of tokens that an owner allowed to a spender.*/ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowance[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowance to a spender. * approve should be called when allowance[_spender] == 0. To increment * allowance value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) validAddress unlocked public returns (bool success) { allowance[msg.sender][_spender] = SafeMath.safeAdd(allowance[msg.sender][_spender], _addedValue); Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowance to a spender. * approve should be called when allowance[_spender] == 0. To decrement * allowance value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) validAddress unlocked public returns (bool success) { uint256 oldValue = allowance[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowance[msg.sender][_spender] = 0; } else { allowance[msg.sender][_spender] = SafeMath.safeSub(oldValue, _subtractedValue); } Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } /* Send coins */ function transfer(address _to, uint256 _value) validAddress unlocked returns (bool success) { _transfer(msg.sender, _to, _value); } /** * 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 != address(0)); require(_value > 0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) validAddress unlocked returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance require(_value > 0); allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); _transfer(_from, _to, _value); return true; } function burn(uint256 _value) validAddress unlocked returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply currentSupply = SafeMath.safeSub(currentSupply,_value); // Updates currentSupply Burn(msg.sender, _value); return true; } function freeze(uint256 _value) validAddress unlocked returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) validAddress unlocked returns (bool success) { require(freezeOf[msg.sender] >= _value); // Check if the sender has enough require(_value > 0); freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); // Updates totalSupply Unfreeze(msg.sender, _value); return true; } function setTokenExchangeRate(uint256 _tokenExchangeRate) onlyOwner external { require(_tokenExchangeRate > 0); require(_tokenExchangeRate != tokenExchangeRate); tokenExchangeRate = _tokenExchangeRate; } function setName(string _name) onlyOwner { name = _name; } function setSymbol(string _symbol) onlyOwner { symbol = _symbol; } /** * @dev Function to lock token transfers * @param _newLockState New lock state * @return A boolean that indicates if the operation was successful. */ function setLock(bool _newLockState) onlyOwner public returns (bool success) { require(_newLockState != locked); locked = _newLockState; return true; } function transferETH() onlyOwner external { require(this.balance > 0); require(owner.send(this.balance)); } // transfer balance to owner function withdrawEther(uint256 amount) onlyOwner { require(msg.sender == owner); owner.transfer(amount); } /** * Fallback function * * The function without name is the default function that is called whenever anyone sends funds to a contract */ function() payable public { require(msg.sender != address(0)); require(msg.value > 0); uint256 tokens = SafeMath.safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = SafeMath.safeAdd(tokenRaised, tokens); balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], tokens); balanceOf[owner] = SafeMath.safeSub(balanceOf[owner], tokens); IssueToken(msg.sender, tokens); Transfer(owner, msg.sender, tokens); } }
TOD1
pragma solidity ^0.4.13; /* taking ideas from FirstBlood token */ contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns (uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns (uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns (uint256) { uint256 z = x * y; assert((x == 0) || (z / x == y)); return z; } } /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract FluencePreSale is Haltable, SafeMath { mapping (address => uint256) public balanceOf; /*/ * Constants /*/ string public constant name = "Fluence Presale Token"; string public constant symbol = "FPT"; uint public constant decimals = 18; // 6% of tokens uint256 public constant SUPPLY_LIMIT = 6000000 ether; // What is given to contributors, <= SUPPLY_LIMIT uint256 public totalSupply; // If soft cap is not reached, refund process is started uint256 public softCap = 1000 ether; // Basic price uint256 public constant basicThreshold = 500 finney; uint public constant basicTokensPerEth = 1500; // Advanced price uint256 public constant advancedThreshold = 5 ether; uint public constant advancedTokensPerEth = 2250; // Expert price uint256 public constant expertThreshold = 100 ether; uint public constant expertTokensPerEth = 3000; // As we have different prices for different amounts, // we keep a mapping of contributions to make refund mapping (address => uint256) public etherContributions; // Max balance of the contract uint256 public etherCollected; // Address to withdraw ether to address public beneficiary; uint public startAtBlock; uint public endAtBlock; // All tokens are sold event GoalReached(uint amountRaised); // Minimal ether cap collected event SoftCapReached(uint softCap); // New contribution received and tokens are issued event NewContribution(address indexed holder, uint256 tokenAmount, uint256 etherAmount); // Ether is taken back event Refunded(address indexed holder, uint256 amount); // If soft cap is reached, withdraw should be available modifier softCapReached { if (etherCollected < softCap) { revert(); } assert(etherCollected >= softCap); _; } // Allow contribution only during presale modifier duringPresale { if (block.number < startAtBlock || block.number > endAtBlock || totalSupply >= SUPPLY_LIMIT) { revert(); } assert(block.number >= startAtBlock && block.number <= endAtBlock && totalSupply < SUPPLY_LIMIT); _; } // Allow withdraw only during refund modifier duringRefund { if(block.number <= endAtBlock || etherCollected >= softCap || this.balance == 0) { revert(); } assert(block.number > endAtBlock && etherCollected < softCap && this.balance > 0); _; } function FluencePreSale(uint _startAtBlock, uint _endAtBlock, uint softCapInEther){ require(_startAtBlock > 0 && _endAtBlock > 0); beneficiary = msg.sender; startAtBlock = _startAtBlock; endAtBlock = _endAtBlock; softCap = softCapInEther * 1 ether; } // Change beneficiary address function setBeneficiary(address to) onlyOwner external { require(to != address(0)); beneficiary = to; } // Withdraw contract's balance to beneficiary account function withdraw() onlyOwner softCapReached external { require(this.balance > 0); beneficiary.transfer(this.balance); } // Process contribution, issue tokens to user function contribute(address _address) private stopInEmergency duringPresale { if(msg.value < basicThreshold && owner != _address) { revert(); } assert(msg.value >= basicThreshold || owner == _address); // Minimal contribution uint256 tokensToIssue; if (msg.value >= expertThreshold) { tokensToIssue = safeMult(msg.value, expertTokensPerEth); } else if (msg.value >= advancedThreshold) { tokensToIssue = safeMult(msg.value, advancedTokensPerEth); } else { tokensToIssue = safeMult(msg.value, basicTokensPerEth); } assert(tokensToIssue > 0); totalSupply = safeAdd(totalSupply, tokensToIssue); // Goal is already reached, can't issue any more tokens if(totalSupply > SUPPLY_LIMIT) { revert(); } assert(totalSupply <= SUPPLY_LIMIT); // Saving ether contributions for the case of refund etherContributions[_address] = safeAdd(etherContributions[_address], msg.value); // Track ether before adding current contribution to notice the event of reaching soft cap uint collectedBefore = etherCollected; etherCollected = safeAdd(etherCollected, msg.value); // Tokens are issued balanceOf[_address] = safeAdd(balanceOf[_address], tokensToIssue); NewContribution(_address, tokensToIssue, msg.value); if (totalSupply == SUPPLY_LIMIT) { GoalReached(etherCollected); } if (etherCollected >= softCap && collectedBefore < softCap) { SoftCapReached(etherCollected); } } function() external payable { contribute(msg.sender); } function refund() stopInEmergency duringRefund external { uint tokensToBurn = balanceOf[msg.sender]; // Sender must have tokens require(tokensToBurn > 0); // Burn balanceOf[msg.sender] = 0; // User contribution amount uint amount = etherContributions[msg.sender]; // Amount must be positive -- refund is not processed yet assert(amount > 0); etherContributions[msg.sender] = 0; // Clear state // Reduce counters etherCollected = safeSubtract(etherCollected, amount); totalSupply = safeSubtract(totalSupply, tokensToBurn); // Process refund. In case of error, it will be thrown msg.sender.transfer(amount); Refunded(msg.sender, amount); } }
TOD1
pragma solidity ^0.4.19; /* PostManager */ contract PostManager { // MARK:- Enums enum State { Inactive, Created, Completed } // MARK:- Structs struct Post { bytes32 jsonHash; // JSON Hash uint value; // Value } // MARK:- Modifiers /* Is the actor the owner of this contract? */ modifier isOwner() { require(msg.sender == owner); _; } /* Is the actor part of the admin group, or are they the owner? */ modifier isAdminGroupOrOwner() { require(containsAdmin(msg.sender) || msg.sender == owner); _; } // MARK:- Properties uint constant version = 1; // Version address owner; // Creator of the contract mapping(address => Post) posts; // Posts mapping(address => address) administrators; // Administrators // MARK:- Events event AdminAdded(address _adminAddress); event AdminDeleted(address _adminAddress); event PostAdded(address _fromAddress); event PostCompleted(address _fromAddress, address _toAddress); // MARK:- Methods /* Constructor */ function PostManager() public { owner = msg.sender; } /* Get contract version */ function getVersion() public constant returns (uint) { return version; } // MARK:- Admin /* Add an administrator */ function addAdmin(address _adminAddress) public isOwner { administrators[_adminAddress] = _adminAddress; AdminAdded(_adminAddress); } /* Delete an administrator */ function deleteAdmin(address _adminAddress) public isOwner { delete administrators[_adminAddress]; AdminDeleted(_adminAddress); } /* Check if an address is an administrator */ function containsAdmin(address _adminAddress) public constant returns (bool) { return administrators[_adminAddress] != 0; } /* Add a post */ function addPost(bytes32 _jsonHash) public payable { // Ensure post not already created require(posts[msg.sender].value != 0); // Create post var post = Post(_jsonHash, msg.value); posts[msg.sender] = post; PostAdded(msg.sender); } /* Complete post */ function completePost(address _fromAddress, address _toAddress) public isAdminGroupOrOwner() { // If owner wants funds, ignore require(_toAddress != _fromAddress); var post = posts[_fromAddress]; // Make sure post exists require(post.value != 0); // Transfer funds _toAddress.transfer(post.value); // Mark complete delete posts[_fromAddress]; // Send event PostCompleted(_fromAddress, _toAddress); } function() public payable { } }
TOD1
pragma solidity ^0.4.17; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data); } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = 'MMT_0.1'; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract RealLandCrowdSale is TokenController, Ownable { using SafeMath for uint; MiniMeToken public tokenContract; uint public PRICE = 10; //1 Ether buys 10 RLD uint public MIN_PURCHASE = 10**17; // 0.1 Ether uint public decimals = 8; uint etherRatio = SafeMath.div(1 ether, 10**decimals); uint256 public saleStartTime = 1512475200; uint256 public saleEndTime = 1517832000; uint256 public totalSupply = 70000000 * 10**decimals; address public team = 0x03c3CD159170Ab0912Cd00d7cACba79694A32127; address public marketting = 0x135B6526943e15fD68EaA05be73f24d641c332D8; address public ipoPlatform = 0x8A8eCFDf0eb6f8406C0AD344a6435D6BAf3110e4; uint256 public teamPercentage = 25000000000000000000; //% * 10**18 uint256 public markettingPercentage = 25000000000000000000; //% * 10**18 uint256 public ipoPlatformPercentage = 50000000000000000000; //% * 10**18 bool public tokensAllocated = false; modifier saleOpen { require((getNow() >= saleStartTime) && (getNow() < saleEndTime)); _; } modifier saleClosed { require(getNow() >= saleEndTime); _; } modifier isMinimum { require(msg.value >= MIN_PURCHASE); _; } function RealLandCrowdSale(address _tokenContract) { tokenContract = MiniMeToken(_tokenContract); } function () payable public { buyTokens(msg.sender); } function buyTokens(address _recipient) payable public saleOpen isMinimum { //Calculate tokens uint tokens = msg.value.mul(PRICE); //Add on any bonus uint bonus = SafeMath.add(100, bonusPercentage()); if (bonus != 100) { tokens = tokens.mul(percent(bonus)).div(percent(100)); } tokens = tokens.div(etherRatio); require(tokenContract.totalSupply().add(tokens) <= bonusCap().mul(10**decimals)); require(tokenContract.generateTokens(_recipient, tokens)); //Transfer Ether to owner owner.transfer(msg.value); } function allocateTokens() public onlyOwner saleClosed { require(!tokensAllocated); tokensAllocated = true; uint256 remainingTokens = totalSupply.sub(tokenContract.totalSupply()); uint256 ipoPlatformTokens = remainingTokens.mul(ipoPlatformPercentage).div(percent(100)); uint256 markettingTokens = remainingTokens.mul(markettingPercentage).div(percent(100)); uint256 teamTokens = remainingTokens.sub(ipoPlatformTokens).sub(markettingTokens); require(tokenContract.generateTokens(team, teamTokens)); require(tokenContract.generateTokens(marketting, markettingTokens)); require(tokenContract.generateTokens(ipoPlatform, ipoPlatformTokens)); } function bonusPercentage() public constant returns(uint256) { uint elapsed = SafeMath.sub(getNow(), saleStartTime); if (elapsed < 1 weeks) return 25; if (elapsed < 2 weeks) return 22; if (elapsed < 3 weeks) return 20; if (elapsed < 4 weeks) return 17; if (elapsed < 5 weeks) return 15; if (elapsed < 6 weeks) return 10; if (elapsed < 7 weeks) return 7; if (elapsed < 8 weeks) return 5; if (elapsed < 9 weeks) return 2; return 0; } function bonusCap() public constant returns(uint256) { uint elapsed = SafeMath.sub(getNow(), saleStartTime); if (elapsed < 1 weeks) return 1000000; if (elapsed < 2 weeks) return 3000000; if (elapsed < 3 weeks) return 5500000; if (elapsed < 4 weeks) return 8500000; if (elapsed < 5 weeks) return 12000000; if (elapsed < 6 weeks) return 17000000; if (elapsed < 7 weeks) return 24000000; if (elapsed < 8 weeks) return 36000000; if (elapsed < 9 weeks) return 56000000; return 70000000; } function percent(uint256 p) internal returns (uint256) { return p.mul(10**18); } //Function is mocked for tests function getNow() internal constant returns (uint256) { return now; } //TokenController implementation /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable public returns(bool) { return false; } /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public saleClosed returns(bool) { return true; } /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public saleClosed returns(bool) { return true; } }
TOD1
pragma solidity 0.4.20; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title StarCoin * * @dev Burnable Ownable ERC20 token */ contract StarCoin is MintableToken { string public constant name = "StarCoin"; string public constant symbol = "STAR"; uint8 public constant decimals = 18; uint public constant INITIAL_SUPPLY = 40000000 * 1 ether; //40M tokens accroding to https://starflow.com/ico/ uint public constant MAXIMUM_SUPPLY = 100000000 * 1 ether; // 100M tokens is maximum according to https://starflow.com/ico/ /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. * */ modifier canTransfer(address _sender) { require(released || transferAgents[_sender]); _; } /** The function can be called only before or after the tokens have been released */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } /** Restrict minting by the MAXIMUM_SUPPLY allowed **/ modifier bellowMaximumSupply(uint _amount) { require(_amount + totalSupply_ < MAXIMUM_SUPPLY); _; } /** * @dev Constructor that gives msg.sender all of existing tokens. */ function StarCoin() { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { require(addr != 0x0); // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } function release() onlyReleaseAgent inReleaseState(false) public { released = true; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { require(addr != 0x0); transferAgents[addr] = state; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { // Call Burnable.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { // Call Burnable.transferForm() return super.transferFrom(_from, _to, _value); } /** * @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, uint _amount) onlyOwner canMint bellowMaximumSupply(_amount) public returns (bool) { return super.mint(_to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { return super.finishMinting(); } } contract InvestorWhiteList is Ownable { mapping (address => bool) public investorWhiteList; mapping (address => address) public referralList; function InvestorWhiteList() { } function addInvestorToWhiteList(address investor) external onlyOwner { require(investor != 0x0 && !investorWhiteList[investor]); investorWhiteList[investor] = true; } function removeInvestorFromWhiteList(address investor) external onlyOwner { require(investor != 0x0 && investorWhiteList[investor]); investorWhiteList[investor] = false; } //when new user will contribute ICO contract will automatically send bonus to referral function addReferralOf(address investor, address referral) external onlyOwner { require(investor != 0x0 && referral != 0x0 && referralList[investor] == 0x0 && investor != referral); referralList[investor] = referral; } function isAllowed(address investor) constant external returns (bool result) { return investorWhiteList[investor]; } function getReferralOf(address investor) constant external returns (address result) { return referralList[investor]; } } contract StarCoinPreSale is Pausable { using SafeMath for uint; string public constant name = "StarCoin Token ICO"; StarCoin public token; address public beneficiary; InvestorWhiteList public investorWhiteList; uint public starEthRate; uint public hardCap; uint public softCap; uint public collected = 0; uint public tokensSold = 0; uint public weiRefunded = 0; uint public startBlock; uint public endBlock; bool public softCapReached = false; bool public crowdsaleFinished = false; mapping (address => uint) public deposited; uint constant VOLUME_20_REF_7 = 5000 ether; uint constant VOLUME_15_REF_6 = 2000 ether; uint constant VOLUME_12d5_REF_5d5 = 1000 ether; uint constant VOLUME_10_REF_5 = 500 ether; uint constant VOLUME_7_REF_4 = 250 ether; uint constant VOLUME_5_REF_3 = 100 ether; event SoftCapReached(uint softCap); event NewContribution(address indexed holder, uint tokenAmount, uint etherAmount); event NewReferralTransfer(address indexed investor, address indexed referral, uint tokenAmount); event Refunded(address indexed holder, uint amount); modifier icoActive() { require(block.number >= startBlock && block.number < endBlock); _; } modifier icoEnded() { require(block.number >= endBlock); _; } modifier minInvestment() { require(msg.value >= 0.1 * 1 ether); _; } modifier inWhiteList() { require(investorWhiteList.isAllowed(msg.sender)); _; } function StarCoinPreSale( uint _hardCapSTAR, uint _softCapSTAR, address _token, address _beneficiary, address _investorWhiteList, uint _baseStarEthPrice, uint _startBlock, uint _endBlock ) { hardCap = _hardCapSTAR.mul(1 ether); softCap = _softCapSTAR.mul(1 ether); token = StarCoin(_token); beneficiary = _beneficiary; investorWhiteList = InvestorWhiteList(_investorWhiteList); startBlock = _startBlock; endBlock = _endBlock; starEthRate = _baseStarEthPrice; } function() payable minInvestment inWhiteList { doPurchase(); } function refund() external icoEnded { require(softCapReached == false); require(deposited[msg.sender] > 0); uint refund = deposited[msg.sender]; deposited[msg.sender] = 0; msg.sender.transfer(refund); weiRefunded = weiRefunded.add(refund); Refunded(msg.sender, refund); } function withdraw() external onlyOwner { require(softCapReached); beneficiary.transfer(collected); token.transfer(beneficiary, token.balanceOf(this)); crowdsaleFinished = true; } function calculateBonus(uint tokens) internal constant returns (uint bonus) { if (msg.value >= VOLUME_20_REF_7) { return tokens.mul(20).div(100); } if (msg.value >= VOLUME_15_REF_6) { return tokens.mul(15).div(100); } if (msg.value >= VOLUME_12d5_REF_5d5) { return tokens.mul(125).div(1000); } if (msg.value >= VOLUME_10_REF_5) { return tokens.mul(10).div(100); } if (msg.value >= VOLUME_7_REF_4) { return tokens.mul(7).div(100); } if (msg.value >= VOLUME_5_REF_3) { return tokens.mul(5).div(100); } return 0; } function calculateReferralBonus(uint tokens) internal constant returns (uint bonus) { if (msg.value >= VOLUME_20_REF_7) { return tokens.mul(7).div(100); } if (msg.value >= VOLUME_15_REF_6) { return tokens.mul(6).div(100); } if (msg.value >= VOLUME_12d5_REF_5d5) { return tokens.mul(55).div(1000); } if (msg.value >= VOLUME_10_REF_5) { return tokens.mul(5).div(100); } if (msg.value >= VOLUME_7_REF_4) { return tokens.mul(4).div(100); } if (msg.value >= VOLUME_5_REF_3) { return tokens.mul(3).div(100); } return 0; } function setNewWhiteList(address newWhiteList) external onlyOwner { require(newWhiteList != 0x0); investorWhiteList = InvestorWhiteList(newWhiteList); } function doPurchase() private icoActive whenNotPaused { require(!crowdsaleFinished); uint tokens = msg.value.mul(starEthRate); uint referralBonus = calculateReferralBonus(tokens); address referral = investorWhiteList.getReferralOf(msg.sender); tokens = tokens.add(calculateBonus(tokens)); uint newTokensSold = tokensSold.add(tokens); if (referralBonus > 0 && referral != 0x0) { newTokensSold = newTokensSold.add(referralBonus); } require(newTokensSold <= hardCap); if (!softCapReached && newTokensSold >= softCap) { softCapReached = true; SoftCapReached(softCap); } collected = collected.add(msg.value); tokensSold = newTokensSold; deposited[msg.sender] = deposited[msg.sender].add(msg.value); token.transfer(msg.sender, tokens); NewContribution(msg.sender, tokens, msg.value); if (referralBonus > 0 && referral != 0x0) { token.transfer(referral, referralBonus); NewReferralTransfer(msg.sender, referral, referralBonus); } } function transferOwnership(address newOwner) onlyOwner icoEnded { super.transferOwnership(newOwner); } }
TOD1
pragma solidity ^0.4.25; contract quiz_game { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; bytes32 questionerPin = 0xbbf3c4a1222554d9c7ff78de2d5fc04ffb3165b9189e4375bf1e790fb10eca8c; function Activate(bytes32 _questionerPin, string _question, string _response) public payable { if(keccak256(_questionerPin)==questionerPin) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; questionerPin = 0x0; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.18; // ==== Open Zeppelin library === /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) pure external { from_; value_; data_; revert(); } } /** * @title Base contract for contracts that should not own things. * @author Remco Bloemen <remco@2π.com> * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or * Owned contracts. See respective base contracts for details. */ contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } // ==== AALM Contracts === contract AALMToken is MintableToken, NoOwner { //MintableToken is StandardToken, Ownable string public symbol = 'AALM'; string public name = 'Alm Token'; uint8 public constant decimals = 18; address founder; //founder address to allow him transfer tokens while minting function init(address _founder) onlyOwner public{ founder = _founder; } /** * Allow transfer only after crowdsale finished */ modifier canTransfer() { require(mintingFinished || msg.sender == founder); _; } function transfer(address _to, uint256 _value) canTransfer public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns (bool) { return super.transferFrom(_from, _to, _value); } } contract AALMCrowdsale is Ownable, CanReclaimToken, Destructible { using SafeMath for uint256; uint32 private constant PERCENT_DIVIDER = 100; struct BulkBonus { uint256 minAmount; //Minimal amount to receive bonus (including this amount) uint32 bonusPercent; //a bonus percent, so that bonus = amount.mul(bonusPercent).div(PERCENT_DIVIDER) } uint64 public startTimestamp; //Crowdsale start timestamp uint64 public endTimestamp; //Crowdsale end timestamp uint256 public minCap; //minimal amount of sold tokens (if not reached - ETH may be refunded) uint256 public hardCap; //total amount of tokens available uint256 public baseRate; //how many tokens will be minted for 1 ETH (like 1000 AALM for 1 ETH) without bonuses uint32 public maxTimeBonusPercent; //A maximum time bonus percent: at the start of crowdsale timeBonus = value.mul(baseRate).mul(maxTimeBonusPercent).div(PERCENT_DIVIDER) uint32 public referrerBonusPercent; //A bonus percent that refferer will receive, so that referrerBonus = value.mul(baseRate).mul(referrerBonusPercent).div(PERCENT_DIVIDER) uint32 public referralBonusPercent; //A bonus percent that refferal will receive, so that referralBonus = value.mul(baseRate).mul(referralBonusPercent).div(PERCENT_DIVIDER) BulkBonus[] public bulkBonuses; //Bulk Bonuses sorted by ether amount (minimal amount first) uint256 public tokensMinted; //total amount of minted tokens uint256 public tokensSold; //total amount of tokens sold(!) on ICO, including all bonuses uint256 public collectedEther; //total amount of ether collected during ICO (without Pre-ICO) mapping(address => uint256) contributions; //amount of ether (in wei)received from a buyer AALMToken public token; TokenVesting public founderVestingContract; //Contract which holds Founder's tokens bool public finalized; function AALMCrowdsale(uint64 _startTimestamp, uint64 _endTimestamp, uint256 _hardCap, uint256 _minCap, uint256 _founderTokensImmediate, uint256 _founderTokensVested, uint256 _vestingDuration, uint256 _baseRate, uint32 _maxTimeBonusPercent, uint32 _referrerBonusPercent, uint32 _referralBonusPercent, uint256[] bulkBonusMinAmounts, uint32[] bulkBonusPercents ) public { require(_startTimestamp > now); require(_startTimestamp < _endTimestamp); startTimestamp = _startTimestamp; endTimestamp = _endTimestamp; require(_hardCap > 0); hardCap = _hardCap; minCap = _minCap; initRatesAndBonuses(_baseRate, _maxTimeBonusPercent, _referrerBonusPercent, _referralBonusPercent, bulkBonusMinAmounts, bulkBonusPercents); token = new AALMToken(); token.init(owner); require(_founderTokensImmediate.add(_founderTokensVested) < _hardCap); mintTokens(owner, _founderTokensImmediate); founderVestingContract = new TokenVesting(owner, endTimestamp, 0, _vestingDuration, false); mintTokens(founderVestingContract, _founderTokensVested); } function initRatesAndBonuses( uint256 _baseRate, uint32 _maxTimeBonusPercent, uint32 _referrerBonusPercent, uint32 _referralBonusPercent, uint256[] bulkBonusMinAmounts, uint32[] bulkBonusPercents ) internal { require(_baseRate > 0); baseRate = _baseRate; maxTimeBonusPercent = _maxTimeBonusPercent; referrerBonusPercent = _referrerBonusPercent; referralBonusPercent = _referralBonusPercent; uint256 prevBulkAmount = 0; require(bulkBonusMinAmounts.length == bulkBonusPercents.length); bulkBonuses.length = bulkBonusMinAmounts.length; for(uint8 i=0; i < bulkBonuses.length; i++){ bulkBonuses[i] = BulkBonus({minAmount:bulkBonusMinAmounts[i], bonusPercent:bulkBonusPercents[i]}); BulkBonus storage bb = bulkBonuses[i]; require(prevBulkAmount < bb.minAmount); prevBulkAmount = bb.minAmount; } } /** * @notice Distribute tokens sold during Pre-ICO * @param beneficiaries Array of beneficiari addresses * @param amounts Array of amounts of tokens to send */ function distributePreICOTokens(address[] beneficiaries, uint256[] amounts) onlyOwner public { require(beneficiaries.length == amounts.length); for(uint256 i=0; i<beneficiaries.length; i++){ mintTokens(beneficiaries[i], amounts[i]); } } /** * @notice Sell tokens directly, without referral bonuses */ function () payable public { sale(msg.sender, msg.value, address(0)); } /** * @notice Sell tokens via RefferalCrowdsale contract * @param beneficiary Original sender (buyer) * @param referrer The partner who referered the buyer */ function referralSale(address beneficiary, address referrer) payable public returns(bool) { sale(beneficiary, msg.value, referrer); return true; } /** * @dev Internal functions to sell tokens * @param beneficiary who should receive tokens (the buyer) * @param value of ether sent by buyer * @param referrer who should receive referrer bonus, if any. Zero address if no referral bonuses should be paid */ function sale(address beneficiary, uint256 value, address referrer) internal { require(crowdsaleOpen()); require(value > 0); collectedEther = collectedEther.add(value); contributions[beneficiary] = contributions[beneficiary].add(value); uint256 amount; if(referrer == address(0)){ amount = getTokensWithBonuses(value, false); } else{ amount = getTokensWithBonuses(value, true); uint256 referrerAmount = getReferrerBonus(value); tokensSold = tokensSold.add(referrerAmount); mintTokens(referrer, referrerAmount); } tokensSold = tokensSold.add(amount); mintTokens(beneficiary, amount); } /** * @notice Mint tokens for purshases with Non-Ether currencies * @param beneficiary whom to send tokend * @param amount how much tokens to send * param message reason why we are sending tokens (not stored anythere, only in transaction itself) */ function saleNonEther(address beneficiary, uint256 amount, string /*message*/) public onlyOwner { mintTokens(beneficiary, amount); } /** * @notice If crowdsale is running */ function crowdsaleOpen() view public returns(bool) { return (!finalized) && (tokensMinted < hardCap) && (startTimestamp <= now) && (now <= endTimestamp); } /** * @notice Calculates how many tokens are left to sale * @return amount of tokens left before hard cap reached */ function getTokensLeft() view public returns(uint256) { return hardCap.sub(tokensMinted); } /** * @notice Calculates how many tokens one should receive at curent time for a specified value of ether * @param value of ether to get bonus for * @param withReferralBonus if should add referral bonus * @return bonus tokens */ function getTokensWithBonuses(uint256 value, bool withReferralBonus) view public returns(uint256) { uint256 amount = value.mul(baseRate); amount = amount.add(getTimeBonus(value)).add(getBulkBonus(value)); if(withReferralBonus){ amount = amount.add(getReferralBonus(value)); } return amount; } /** * @notice Calculates current time bonus * @param value of ether to get bonus for * @return bonus tokens */ function getTimeBonus(uint256 value) view public returns(uint256) { uint256 maxBonus = value.mul(baseRate).mul(maxTimeBonusPercent).div(PERCENT_DIVIDER); return maxBonus.mul(endTimestamp - now).div(endTimestamp - startTimestamp); } /** * @notice Calculates a bulk bonus for a specified value of ether * @param value of ether to get bonus for * @return bonus tokens */ function getBulkBonus(uint256 value) view public returns(uint256) { for(uint8 i=uint8(bulkBonuses.length); i > 0; i--){ uint8 idx = i - 1; //if i = bulkBonuses.length-1 to 0, i-- fails on last iteration if (value >= bulkBonuses[idx].minAmount) { return value.mul(baseRate).mul(bulkBonuses[idx].bonusPercent).div(PERCENT_DIVIDER); } } return 0; } /** * @notice Calculates referrer bonus * @param value of ether to get bonus for * @return bonus tokens */ function getReferrerBonus(uint256 value) view public returns(uint256) { return value.mul(baseRate).mul(referrerBonusPercent).div(PERCENT_DIVIDER); } /** * @notice Calculates referral bonus * @param value of ether to get bonus for * @return bonus tokens */ function getReferralBonus(uint256 value) view public returns(uint256) { return value.mul(baseRate).mul(referralBonusPercent).div(PERCENT_DIVIDER); } /** * @dev Helper function to mint tokens and increase tokensMinted counter */ function mintTokens(address beneficiary, uint256 amount) internal { tokensMinted = tokensMinted.add(amount); require(tokensMinted <= hardCap); assert(token.mint(beneficiary, amount)); } /** * @notice Sends all contributed ether back if minimum cap is not reached by the end of crowdsale */ function refund() public returns(bool){ return refundTo(msg.sender); } function refundTo(address beneficiary) public returns(bool) { require(contributions[beneficiary] > 0); require(finalized || (now > endTimestamp)); require(tokensSold < minCap); uint256 _refund = contributions[beneficiary]; contributions[beneficiary] = 0; beneficiary.transfer(_refund); return true; } /** * @notice Closes crowdsale, finishes minting (allowing token transfers), transfers token ownership to the owner */ function finalizeCrowdsale() public onlyOwner { finalized = true; token.finishMinting(); token.transferOwnership(owner); if(tokensSold >= minCap && this.balance > 0){ owner.transfer(this.balance); } } /** * @notice Claim collected ether without closing crowdsale */ function claimEther() public onlyOwner { require(tokensSold >= minCap); owner.transfer(this.balance); } }
TOD1
pragma solidity ^0.4.20; contract ETH_QUIZ { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 3 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function set_game(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.25; contract go_to_play { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value > 2 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; bytes32 questionerPin = 0x9953786a5ed139ad55c6fbf08d1114c24c6a90636c0dfc934d5b3f718a87a74f; function Activate(bytes32 _questionerPin, string _question, string _response) public payable { if(keccak256(_questionerPin)==questionerPin) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; questionerPin = 0x0; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity >=0.4.10; /* ---------------------------------------------------------------------------------------- Dev: "Owned" to ensure control of contracts Identical to https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol ---------------------------------------------------------------------------------------- */ contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } /* ---------------------------------------------------------------------------------------- Dev: SafeMath library Identical to https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol ---------------------------------------------------------------------------------------- */ library SafeMath { function safeMul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function safeSub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); // Ensuring no negatives return a - b; } function safeAdd(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a && c>=b); return c; } } /* ---------------------------------------------------------------------------------------- Dev: ESG Asset Holder is called when the token "burn" function is called Sum: Locked to false so users cannot burn their tokens until the Asset Contract is put in place with value. ---------------------------------------------------------------------------------------- */ contract ESGAssetHolder { function burn(address _holder, uint _amount) returns (bool result) { _holder = 0x0; // To avoid variable not used issue on deployment _amount = 0; // To avoid variable not used issue on deployment return false; } } /* ---------------------------------------------------------------------------------------- Dev: The Esports Gold Token: ERC20 standard token with MINT and BURN functions Func: Mint, Approve, Transfer, TransferFrom Note: Mint function takes UNITS of tokens to mint as ICO event is set to have a minimum contribution of 1 token. All other functions (transfer etc), the value to transfer is the FULL DECIMAL value The user is only ever presented with the latter option, therefore should avoid any confusion. ---------------------------------------------------------------------------------------- */ contract ESGToken is Owned { string public name = "ESG Token"; // Name of token string public symbol = "ESG"; // Token symbol uint256 public decimals = 3; // Decimals for the token uint256 public currentSupply; // Current supply of tokens uint256 public supplyCap; // Hard cap on supply of tokens address public ICOcontroller; // Controlling contract from ICO address public timelockTokens; // Address for locked management tokens bool public tokenParametersSet; // Ensure that parameters required are set bool public controllerSet; // Ensure that ICO controller is set mapping (address => uint256) public balanceOf; // Balances of addresses mapping (address => mapping (address => uint)) public allowance; // Allowances from addresses mapping (address => bool) public frozenAccount; // Safety mechanism modifier onlyControllerOrOwner() { // Ensures that only contracts can manage key functions require(msg.sender == ICOcontroller || msg.sender == owner); _; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Mint(address owner, uint amount); event FrozenFunds(address target, bool frozen); event Burn(address coinholder, uint amount); /* ---------------------------------------------------------------------------------------- Dev: Constructor param: Owner: Address of owner Name: Esports Gold Token Sym: ESG_TKN Dec: 3 Cap: Hard coded cap to ensure excess tokens cannot be minted Other parameters have been set up as a separate function to help lower initial gas deployment cost. ---------------------------------------------------------------------------------------- */ function ESGToken() { currentSupply = 0; // Starting supply is zero supplyCap = 0; // Hard cap supply in Tokens set by ICO tokenParametersSet = false; // Ensure parameters are set controllerSet = false; // Ensure controller is set } /* ---------------------------------------------------------------------------------------- Dev: Key parameters to setup for ICO event Param: _ico Address of the ICO Event contract to ensure the ICO event can control the minting function ---------------------------------------------------------------------------------------- */ function setICOController(address _ico) onlyOwner { // ICO event address is locked in require(_ico != 0x0); ICOcontroller = _ico; controllerSet = true; } /* ---------------------------------------------------------------------------------------- NEW Dev: Address for the timelock tokens to be held Param: _timelockAddr Address of the timelock contract that will hold the locked tokens ---------------------------------------------------------------------------------------- */ function setParameters(address _timelockAddr) onlyOwner { require(_timelockAddr != 0x0); timelockTokens = _timelockAddr; tokenParametersSet = true; } function parametersAreSet() constant returns (bool) { return tokenParametersSet && controllerSet; } /* ---------------------------------------------------------------------------------------- Dev: Set the total number of Tokens that can be minted Param: _supplyCap The number of tokens (in whole units) that can be minted. This number then gets increased by the decimal number ---------------------------------------------------------------------------------------- */ function setTokenCapInUnits(uint256 _supplyCap) onlyControllerOrOwner { // Supply cap in UNITS assert(_supplyCap > 0); supplyCap = SafeMath.safeMul(_supplyCap, (10**decimals)); } /* ---------------------------------------------------------------------------------------- Dev: Mint the number of tokens for the timelock contract Param: _mMentTkns Number of tokens in whole units that need to be locked into the Timelock ---------------------------------------------------------------------------------------- */ function mintLockedTokens(uint256 _mMentTkns) onlyControllerOrOwner { assert(_mMentTkns > 0); assert(tokenParametersSet); mint(timelockTokens, _mMentTkns); } /* ---------------------------------------------------------------------------------------- Dev: Gets the balance of the address owner Param: _owner Address of the owner querying their balance ---------------------------------------------------------------------------------------- */ function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOf[_owner]; } /* ---------------------------------------------------------------------------------------- Dev: Mint ESG Tokens by controller Control: OnlyControllers. ICO event needs to be able to control the minting function Param: Address Address for tokens to be minted to Amount Number of tokens to be minted (in whole UNITS. Min minting is 1 token) Minimum ETH contribution in ICO event is 0.01ETH at 100 tokens per ETH ---------------------------------------------------------------------------------------- */ function mint(address _address, uint _amount) onlyControllerOrOwner { require(_address != 0x0); uint256 amount = SafeMath.safeMul(_amount, (10**decimals)); // Tokens minted using unit parameter supplied // Ensure that supplyCap is set and that new tokens don't breach cap assert(supplyCap > 0 && amount > 0 && SafeMath.safeAdd(currentSupply, amount) <= supplyCap); balanceOf[_address] = SafeMath.safeAdd(balanceOf[_address], amount); // Add tokens to address currentSupply = SafeMath.safeAdd(currentSupply, amount); // Add to supply Mint(_address, amount); } /* ---------------------------------------------------------------------------------------- Dev: ERC20 standard transfer function Param: _to Address to send to _value Number of tokens to be sent - in FULL decimal length Ref: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/BasicToken.sol ---------------------------------------------------------------------------------------- */ function transfer(address _to, uint _value) returns (bool success) { require(!frozenAccount[msg.sender]); // Ensure account is not frozen /* Update balances from "from" and "to" addresses with the tokens transferred safeSub method ensures that address sender has enough tokens to send */ balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; } /* ---------------------------------------------------------------------------------------- Dev: ERC20 standard transferFrom function Param: _from Address to send from _to Address to send to Amount Number of tokens to be sent - in FULL decimal length ---------------------------------------------------------------------------------------- */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); // Check account is not frozen /* Ensure sender has been authorised to send the required number of tokens */ if (allowance[_from][msg.sender] < _value) return false; /* Update allowance of sender to reflect tokens sent */ allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); /* Update balances from "from" and "to" addresses with the tokens transferred safeSub method ensures that address sender has enough tokens to send */ balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); return true; } /* ---------------------------------------------------------------------------------------- Dev: ERC20 standard approve function Param: _spender Address of sender who is approved _value The number of tokens (full decimals) that are approved ---------------------------------------------------------------------------------------- */ function approve(address _spender, uint256 _value) // FULL DECIMALS OF TOKENS returns (bool success) { require(!frozenAccount[msg.sender]); // Check account is not frozen /* Requiring the user to set to zero before resetting to nonzero */ if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) { return false; } allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* ---------------------------------------------------------------------------------------- Dev: Function to check the amount of tokens that the owner has allowed the "spender" to transfer Param: _owner Address of the authoriser who owns the tokens _spender Address of sender who will be authorised to spend the tokens ---------------------------------------------------------------------------------------- */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowance[_owner][_spender]; } /* ---------------------------------------------------------------------------------------- Dev: As ESG is aiming to be a regulated betting operator. Regulatory hurdles may require this function if an account on the betting platform, using the token, breaches a regulatory requirement. ESG can then engage with the account holder to get it unlocked This does not stop the token accruing value from its share of the Asset Contract Param: _target Address of account _freeze Boolean to lock/unlock account Ref: This is a replica of the code as per https://ethereum.org/token ---------------------------------------------------------------------------------------- */ function freezeAccount(address target, bool freeze) onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /* ---------------------------------------------------------------------------------------- Dev: Burn function: User is able to burn their token for a share of the ESG Asset Contract Note: Deployed with the ESG Asset Contract set to false to ensure token holders cannot accidentally burn their tokens for zero value Param: _amount Number of tokens (full decimals) that should be burnt Ref: Based on the open source TokenCard Burn function. A copy can be found at https://github.com/bokkypoobah/TokenCardICOAnalysis ---------------------------------------------------------------------------------------- */ function burn(uint _amount) returns (bool result) { if (_amount > balanceOf[msg.sender]) return false; // If owner has enough to burn /* Remove tokens from circulation Update sender's balance of tokens */ balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _amount); currentSupply = SafeMath.safeSub(currentSupply, _amount); // Call burn function result = esgAssetHolder.burn(msg.sender, _amount); require(result); Burn(msg.sender, _amount); } /* ---------------------------------------------------------------------------------------- Dev: Section of the contract that links to the ESG Asset Contract Note: Deployed with the ESG Asset Contract set to false to ensure token holders cannot accidentally burn their tokens for zero value Param: _amount Number of tokens (full decimals) that should be burnt Ref: Based on the open source TokenCard Burn function. A copy can be found at https://github.com/bokkypoobah/TokenCardICOAnalysis ---------------------------------------------------------------------------------------- */ ESGAssetHolder esgAssetHolder; // Holds the accumulated asset contract bool lockedAssetHolder; // Will be locked to stop tokenholder to be upgraded function lockAssetHolder() onlyOwner { // Locked once deployed lockedAssetHolder = true; } function setAssetHolder(address _assetAdress) onlyOwner { // Used to lock in the Asset Contract assert(!lockedAssetHolder); // Check that we haven't locked the asset holder yet esgAssetHolder = ESGAssetHolder(_assetAdress); } } /* ---------------------------------------------------------------------------------------- Dev: Vested token option for management - locking in account holders for 2 years Ref: Identical to OpenZeppelin open source contract except releaseTime is locked in https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/TokenTimelock.sol ---------------------------------------------------------------------------------------- */ contract TokenTimelock { // ERC20 basic token contract being held ESGToken token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; function TokenTimelock(address _token, address _beneficiary) { require(_token != 0x0); require(_beneficiary != 0x0); token = ESGToken(_token); //token = _token; beneficiary = _beneficiary; releaseTime = now + 2 years; } /* Show the balance in the timelock for transparency Therefore transparent view of the whitepaper allotted management tokens */ function lockedBalance() public constant returns (uint256) { return token.balanceOf(this); } /* Transfers tokens held by timelock to beneficiary */ function release() { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.transfer(beneficiary, amount); } } /* ---------------------------------------------------------------------------------------- Dev: ICO Controller event ICO Controller manages the ICO event including payable functions that trigger mint, Refund collections, Base target and ICO discount rates for deposits before Base Target Ref: Modified version of crowdsale contract with refund option (if base target not reached) https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/crowdsale/Crowdsale.sol https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/crowdsale/RefundVault.sol ---------------------------------------------------------------------------------------- */ contract ICOEvent is Owned { ESGToken public token; // ESG TOKEN used for Deposit, Claims, Set Address uint256 public startTime = 0; // StartTime default uint256 public endTime; // End time is start + duration uint256 duration; // Duration in days for ICO bool parametersSet; // Ensure paramaters are locked in before starting ICO bool supplySet; // Ensure token supply set address holdingAccount = 0x0; // Address for successful closing of ICO uint256 public totalTokensMinted; // To record total number of tokens minted // For purchasing tokens uint256 public rate_toTarget; // Rate of tokens per 1 ETH contributed to the base target uint256 public rate_toCap; // Rate of tokens from base target to cap per 1 ETH uint256 public totalWeiContributed = 0; // Tracks total Ether contributed in WEI uint256 public minWeiContribution = 0.01 ether; // At 100:1ETH means 1 token = the minimum contribution uint256 constant weiEtherConversion = 10**18; // To allow inputs for setup in ETH for simplicity // Cap parameters uint256 public baseTargetInWei; // Target for bonus rate of tokens uint256 public icoCapInWei; // Max cap of the ICO in Wei event logPurchase (address indexed purchaser, uint value, uint256 tokens); enum State { Active, Refunding, Closed } // Allows control of the ICO state State public state; mapping (address => uint256) public deposited; // Mapping for address deposit amounts mapping (address => uint256) public tokensIssued; // Mapping for address token amounts /* ---------------------------------------------------------------------------------------- Dev: Constructor param: Parameters are set individually after construction to lower initial deployment gas State: set default state to active ---------------------------------------------------------------------------------------- */ function ICOEvent() { state = State.Active; totalTokensMinted = 0; parametersSet = false; supplySet = false; } /* ---------------------------------------------------------------------------------------- Dev: This section is to set parameters for the ICO control by the owner Param: _tokenAddress Address of the ESG Token contract that has been deployed _target_rate Number of tokens (in units, excl token decimals) per 1 ETH contribution up to the ETH base target _cap_rate Number of tokens (in units, excl token decimals) per 1 ETH contribution from the base target to the ICO cap _baseTarget Number of ETH to reach the base target. ETH is refunded if base target is not reached _cap Total ICO cap in ETH. No further ETH can be deposited beyond this _holdingAccount Address of the beneficiary account on a successful ICO _duration Duration of ICO in days ---------------------------------------------------------------------------------------- */ function ICO_setParameters(address _tokenAddress, uint256 _target_rate, uint256 _cap_rate, uint256 _baseTarget, uint256 _cap, address _holdingAccount, uint256 _duration) onlyOwner { require(_target_rate > 0 && _cap_rate > 0); require(_baseTarget >= 0); require(_cap > 0); require(_duration > 0); require(_holdingAccount != 0x0); require(_tokenAddress != 0x0); rate_toTarget = _target_rate; rate_toCap = _cap_rate; token = ESGToken(_tokenAddress); baseTargetInWei = SafeMath.safeMul(_baseTarget, weiEtherConversion); icoCapInWei = SafeMath.safeMul(_cap, weiEtherConversion); holdingAccount = _holdingAccount; duration = SafeMath.safeMul(_duration, 1 days); parametersSet = true; } /* ---------------------------------------------------------------------------------------- Dev: Ensure the ICO parameters are set before initialising start of ICO ---------------------------------------------------------------------------------------- */ function eventConfigured() internal constant returns (bool) { return parametersSet && supplySet; } /* ---------------------------------------------------------------------------------------- Dev: Starts the ICO. Initialises starttime at now - current block timestamp ---------------------------------------------------------------------------------------- */ function ICO_start() onlyOwner { assert (eventConfigured()); startTime = now; endTime = SafeMath.safeAdd(startTime, duration); } function ICO_start_future(uint _startTime) onlyOwner { assert(eventConfigured()); require(_startTime > now); startTime = _startTime; endTime = SafeMath.safeAdd(startTime, duration); } function ICO_token_supplyCap() onlyOwner { require(token.parametersAreSet()); // Ensure parameters are set in the token // Method to calculate number of tokens required to base target uint256 targetTokens = SafeMath.safeMul(baseTargetInWei, rate_toTarget); targetTokens = SafeMath.safeDiv(targetTokens, weiEtherConversion); // Method to calculate number of tokens required between base target and cap uint256 capTokens = SafeMath.safeSub(icoCapInWei, baseTargetInWei); capTokens = SafeMath.safeMul(capTokens, rate_toCap); capTokens = SafeMath.safeDiv(capTokens, weiEtherConversion); /* Hard setting for 10% of base target tokens as per Whitepaper as M'ment incentive This is set to only a percentage of the base target, not overall cap Don't need to divide by weiEtherConversion as already in tokens */ uint256 mmentTokens = SafeMath.safeMul(targetTokens, 10); mmentTokens = SafeMath.safeDiv(mmentTokens, 100); // Total supply for the ICO will be available tokens + m'ment reserve uint256 tokens_available = SafeMath.safeAdd(capTokens, targetTokens); uint256 total_Token_Supply = SafeMath.safeAdd(tokens_available, mmentTokens); // Tokens in UNITS token.setTokenCapInUnits(total_Token_Supply); // Set supply cap and mint to timelock token.mintLockedTokens(mmentTokens); // Lock in the timelock tokens supplySet = true; } /* ---------------------------------------------------------------------------------------- Dev: Fallback payable function if ETH is transferred to the ICO contract param: No parameters - calls deposit(Address) with msg.sender ---------------------------------------------------------------------------------------- */ function () payable { deposit(msg.sender); } /* ---------------------------------------------------------------------------------------- Dev: Deposit function. User needs to ensure that the purchase is within ICO cap range Function checks that the ICO is still active, that the cap hasn't been reached and the address provided is != 0x0. Calls: getPreTargetContribution(value) This function calculates how much (if any) of the value transferred falls within the base target goal and qualifies for the target rate of tokens Token.mint(address, number) Calls the token mint function in the ESGToken contract param: _for Address of the sender for tokens ---------------------------------------------------------------------------------------- */ function deposit(address _for) payable { /* Checks to ensure purchase is valid. A purchase that breaches the cap is not allowed */ require(validPurchase(msg.value)); // Checks time, value purchase is within Cap and address != 0x0 require(state == State.Active); // IE not in refund or closed require(!ICO_Ended()); // Checks time closed or cap reached /* Calculates if any of the value falls before the base target so that the correct Token : ETH rate can be applied to the value transferred */ uint256 targetContribution = getPreTargetContribution(msg.value); // Contribution before base target uint256 capContribution = SafeMath.safeSub(msg.value, targetContribution); // Contribution above base target totalWeiContributed = SafeMath.safeAdd(totalWeiContributed, msg.value); // Update total contribution /* Calculate total tokens earned by rate * contribution (in Wei) Multiplication first ensures that dividing back doesn't truncate/round */ uint256 targetTokensToMint = SafeMath.safeMul(targetContribution, rate_toTarget); // Discount rate tokens uint256 capTokensToMint = SafeMath.safeMul(capContribution, rate_toCap); // Standard rate tokens uint256 tokensToMint = SafeMath.safeAdd(targetTokensToMint, capTokensToMint); // Total tokens tokensToMint = SafeMath.safeDiv(tokensToMint, weiEtherConversion); // Get tokens in units totalTokensMinted = SafeMath.safeAdd(totalTokensMinted, tokensToMint); // Update total tokens minted deposited[_for] = SafeMath.safeAdd(deposited[_for], msg.value); // Log deposit and inc of refunds tokensIssued[_for] = SafeMath.safeAdd(tokensIssued[_for], tokensToMint); // Log tokens issued token.mint(_for, tokensToMint); // Mint tokens from Token Mint logPurchase(_for, msg.value, tokensToMint); } /* ---------------------------------------------------------------------------------------- Dev: Calculates how much of the ETH contributed falls before the base target cap to therefore calculate the correct rates of Token to be issued param: _valueSent The value of ETH transferred on the payable function returns: uint256 The value that falls before the base target ---------------------------------------------------------------------------------------- */ function getPreTargetContribution(uint256 _valueSent) internal returns (uint256) { uint256 targetContribution = 0; // Default return if (totalWeiContributed < baseTargetInWei) { if (SafeMath.safeAdd(totalWeiContributed, _valueSent) > baseTargetInWei) { // Contribution straddles baseTarget targetContribution = SafeMath.safeSub(baseTargetInWei, totalWeiContributed); // IF #1 means always +ve } else { targetContribution = _valueSent; } } return targetContribution; } /* ---------------------------------------------------------------------------------------- Dev: Public viewable functions to show key parameters ---------------------------------------------------------------------------------------- */ // Is the ICO Live: time live, state Active function ICO_Live() public constant returns (bool) { return (now >= startTime && now < endTime && state == State.Active); } // Time is valid, purchase isn't zero and cap won't be breached function validPurchase(uint256 _value) payable returns (bool) { // Known true bool validTime = (now >= startTime && now < endTime); // Must be true bool validAmount = (_value >= minWeiContribution); bool withinCap = SafeMath.safeAdd(totalWeiContributed, _value) <= icoCapInWei; return validTime && validAmount && withinCap; } // ICO has ended function ICO_Ended() public constant returns (bool) { bool capReached = (totalWeiContributed >= icoCapInWei); bool stateValid = state == State.Closed; return (now >= endTime) || capReached || stateValid; } // Wei remaining until ICO is capped function Wei_Remaining_To_ICO_Cap() public constant returns (uint256) { return (icoCapInWei - totalWeiContributed); } // Shows if the base target cap has been reached function baseTargetReached() public constant returns (bool) { return totalWeiContributed >= baseTargetInWei; } // Shows if the cap has been reached function capReached() public constant returns (bool) { return totalWeiContributed == icoCapInWei; } /* ---------------------------------------------------------------------------------------- Dev: This section controls closing of the ICO. The state is set to closed so that the ICO is shown as ended. Based on the function from open zeppelin contracts: RefundVault + RefundableCrowdsale Ref: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/crowdsale/RefundableCrowdsale.sol https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/crowdsale/RefundVault.sol ---------------------------------------------------------------------------------------- */ event Closed(); // Set closed ICO and transfer balance to holding account function close() onlyOwner { require((now >= endTime) || (totalWeiContributed >= icoCapInWei)); require(state==State.Active); state = State.Closed; Closed(); holdingAccount.transfer(this.balance); } }
TOD1
pragma solidity ^0.4.13; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Autonomy is Ownable { address public congress; bool init = false; modifier onlyCongress() { require(msg.sender == congress); _; } /** * @dev initialize a Congress contract address for this token * * @param _congress address the congress contract address */ function initialCongress(address _congress) onlyOwner public { require(!init); require(_congress != address(0)); congress = _congress; init = true; } /** * @dev set a Congress contract address for this token * must change this address by the last congress contract * * @param _congress address the congress contract address */ function changeCongress(address _congress) onlyCongress public { require(_congress != address(0)); congress = _congress; } } contract withdrawable is Ownable { event ReceiveEther(address _from, uint256 _value); event WithdrawEther(address _to, uint256 _value); event WithdrawToken(address _token, address _to, uint256 _value); /** * @dev recording receiving ether from msn.sender */ function () payable public { emit ReceiveEther(msg.sender, msg.value); } /** * @dev withdraw,send ether to target * @param _to is where the ether will be sent to * _amount is the number of the ether */ function withdraw(address _to, uint _amount) public onlyOwner returns (bool) { require(_to != address(0)); _to.transfer(_amount); emit WithdrawEther(_to, _amount); return true; } /** * @dev withdraw tokens, send tokens to target * * @param _token the token address that will be withdraw * @param _to is where the tokens will be sent to * _value is the number of the token */ function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_token != address(0)); ERC20 tk = ERC20(_token); tk.transfer(_to, _value); emit WithdrawToken(_token, _to, _value); return true; } /** * @dev receive approval from an ERC20 token contract, and then gain the tokens, * then take a record * * @param _from address The address which you want to send tokens from * @param _value uint256 the amounts of tokens to be sent * @param _token address the ERC20 token address * @param _extraData bytes the extra data for the record */ // function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public { // require(_token != address(0)); // require(_from != address(0)); // ERC20 tk = ERC20(_token); // require(tk.transferFrom(_from, this, _value)); // emit ReceiveDeposit(_from, _value, _token, _extraData); // } } contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract TokenDestructible is Ownable { function TokenDestructible() public payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract OwnerContract is Claimable { Claimable public ownedContract; address internal origOwner; /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function bindContract(address _contract) onlyOwner public returns (bool) { require(_contract != address(0)); ownedContract = Claimable(_contract); origOwner = ownedContract.owner(); // take ownership of the owned contract ownedContract.claimOwnership(); return true; } /** * @dev change the owner of the contract from this contract address to the original one. * */ function transferOwnershipBack() onlyOwner public { ownedContract.transferOwnership(origOwner); ownedContract = Claimable(address(0)); origOwner = address(0); } /** * @dev change the owner of the contract from this contract address to another one. * * @param _nextOwner the contract address that will be next Owner of the original Contract */ function changeOwnershipto(address _nextOwner) onlyOwner public { ownedContract.transferOwnership(_nextOwner); ownedContract = Claimable(address(0)); origOwner = address(0); } } contract DepositWithdraw is Claimable, Pausable, withdrawable { using SafeMath for uint256; /** * transaction record */ struct TransferRecord { uint256 timeStamp; address account; uint256 value; } /** * accumulated transferring amount record */ struct accumulatedRecord { uint256 mul; uint256 count; uint256 value; } TransferRecord[] deposRecs; // record all the deposit tx data TransferRecord[] withdrRecs; // record all the withdraw tx data accumulatedRecord dayWithdrawRec; // accumulated amount record for one day accumulatedRecord monthWithdrawRec; // accumulated amount record for one month address wallet; // the binded withdraw address event ReceiveDeposit(address _from, uint256 _value, address _token, bytes _extraData); /** * @dev constructor of the DepositWithdraw contract * @param _wallet the binded wallet address to this depositwithdraw contract */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } /** * @dev set the default wallet address * @param _wallet the default wallet address binded to this deposit contract */ function setWithdrawWallet(address _wallet) onlyOwner public returns (bool) { require(_wallet != address(0)); wallet = _wallet; return true; } /** * @dev util function to change bytes data to bytes32 data * @param _data the bytes data to be converted */ function bytesToBytes32(bytes _data) public pure returns (bytes32 result) { assembly { result := mload(add(_data, 32)) } } /** * @dev receive approval from an ERC20 token contract, take a record * * @param _from address The address which you want to send tokens from * @param _value uint256 the amounts of tokens to be sent * @param _token address the ERC20 token address * @param _extraData bytes the extra data for the record */ function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) onlyOwner whenNotPaused public { require(_token != address(0)); require(_from != address(0)); ERC20 tk = ERC20(_token); require(tk.transferFrom(_from, this, _value)); bytes32 timestamp = bytesToBytes32(_extraData); deposRecs.push(TransferRecord(uint256(timestamp), _from, _value)); emit ReceiveDeposit(_from, _value, _token, _extraData); } /** * @dev withdraw tokens, send tokens to target * * @param _token the token address that will be withdraw * @param _params the limitation parameters for withdraw * @param _time the timstamp of the withdraw time * @param _to is where the tokens will be sent to * _value is the number of the token * _fee is the amount of the transferring costs * _tokenReturn is the address that return back the tokens of the _fee */ function withdrawToken(address _token, address _params, uint256 _time, address _to, uint256 _value, uint256 _fee, address _tokenReturn) public onlyOwner whenNotPaused returns (bool) { require(_to != address(0)); require(_token != address(0)); require(_value > _fee); // require(_tokenReturn != address(0)); DRCWalletMgrParams params = DRCWalletMgrParams(_params); require(_value <= params.singleWithdraw()); uint256 daysCount = _time.div(86400); if (daysCount <= dayWithdrawRec.mul) { dayWithdrawRec.count = dayWithdrawRec.count.add(1); dayWithdrawRec.value = dayWithdrawRec.value.add(_value); require(dayWithdrawRec.count <= params.dayWithdrawCount()); require(dayWithdrawRec.value <= params.dayWithdraw()); } else { dayWithdrawRec.mul = daysCount; dayWithdrawRec.count = 1; dayWithdrawRec.value = _value; } uint256 monthsCount = _time.div(86400 * 30); if (monthsCount <= monthWithdrawRec.mul) { monthWithdrawRec.count = monthWithdrawRec.count.add(1); monthWithdrawRec.value = monthWithdrawRec.value.add(_value); require(monthWithdrawRec.value <= params.monthWithdraw()); } else { monthWithdrawRec.mul = monthsCount; monthWithdrawRec.count = 1; monthWithdrawRec.value = _value; } ERC20 tk = ERC20(_token); uint256 realAmount = _value.sub(_fee); require(tk.transfer(_to, realAmount)); if (_tokenReturn != address(0) && _fee > 0) { require(tk.transfer(_tokenReturn, _fee)); } withdrRecs.push(TransferRecord(_time, _to, realAmount)); emit WithdrawToken(_token, _to, realAmount); return true; } /** * @dev withdraw tokens, send tokens to target default wallet * * @param _token the token address that will be withdraw * @param _params the limitation parameters for withdraw * @param _time the timestamp occur the withdraw record * @param _value is the number of the token * _fee is the amount of the transferring costs * —tokenReturn is the address that return back the tokens of the _fee */ function withdrawTokenToDefault(address _token, address _params, uint256 _time, uint256 _value, uint256 _fee, address _tokenReturn) public onlyOwner whenNotPaused returns (bool) { return withdrawToken(_token, _params, _time, wallet, _value, _fee, _tokenReturn); } /** * @dev get the Deposit records number * */ function getDepositNum() public view returns (uint256) { return deposRecs.length; } /** * @dev get the one of the Deposit records * * @param _ind the deposit record index */ function getOneDepositRec(uint256 _ind) public view returns (uint256, address, uint256) { require(_ind < deposRecs.length); return (deposRecs[_ind].timeStamp, deposRecs[_ind].account, deposRecs[_ind].value); } /** * @dev get the withdraw records number * */ function getWithdrawNum() public view returns (uint256) { return withdrRecs.length; } /** * @dev get the one of the withdraw records * * @param _ind the withdraw record index */ function getOneWithdrawRec(uint256 _ind) public view returns (uint256, address, uint256) { require(_ind < withdrRecs.length); return (withdrRecs[_ind].timeStamp, withdrRecs[_ind].account, withdrRecs[_ind].value); } } contract DRCWalletManager is OwnerContract, withdrawable, Destructible, TokenDestructible { using SafeMath for uint256; /** * withdraw wallet description */ struct WithdrawWallet { bytes32 name; address walletAddr; } /** * Deposit data storage */ struct DepositRepository { // uint256 balance; uint256 frozen; WithdrawWallet[] withdrawWallets; // mapping (bytes32 => address) withdrawWallets; } mapping (address => DepositRepository) depositRepos; mapping (address => address) walletDeposits; mapping (address => bool) public frozenDeposits; ERC20 public tk; // the token will be managed DRCWalletMgrParams params; // the parameters that the management needs event CreateDepositAddress(address indexed _wallet, address _deposit); event FrozenTokens(address indexed _deposit, uint256 _value); event ChangeDefaultWallet(address indexed _oldWallet, address _newWallet); /** * @dev withdraw tokens, send tokens to target default wallet * * @param _token the token address that will be withdraw * @param _walletParams the wallet management parameters */ function bindToken(address _token, address _walletParams) onlyOwner public returns (bool) { require(_token != address(0)); require(_walletParams != address(0)); tk = ERC20(_token); params = DRCWalletMgrParams(_walletParams); return true; } /** * @dev create deposit contract address for the default withdraw wallet * * @param _wallet the binded default withdraw wallet address */ function createDepositContract(address _wallet) onlyOwner public returns (address) { require(_wallet != address(0)); DepositWithdraw deposWithdr = new DepositWithdraw(_wallet); // new contract for deposit address _deposit = address(deposWithdr); walletDeposits[_wallet] = _deposit; WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; withdrawWalletList.push(WithdrawWallet("default wallet", _wallet)); // depositRepos[_deposit].balance = 0; depositRepos[_deposit].frozen = 0; emit CreateDepositAddress(_wallet, address(deposWithdr)); return deposWithdr; } /** * @dev get deposit contract address by using the default withdraw wallet * * @param _wallet the binded default withdraw wallet address */ function getDepositAddress(address _wallet) onlyOwner public view returns (address) { require(_wallet != address(0)); address deposit = walletDeposits[_wallet]; return deposit; } /** * @dev get deposit balance and frozen amount by using the deposit address * * @param _deposit the deposit contract address */ function getDepositInfo(address _deposit) onlyOwner public view returns (uint256, uint256) { require(_deposit != address(0)); uint256 _balance = tk.balanceOf(_deposit); uint256 frozenAmount = depositRepos[_deposit].frozen; // depositRepos[_deposit].balance = _balance; return (_balance, frozenAmount); } /** * @dev get the number of withdraw wallet addresses bindig to the deposit contract address * * @param _deposit the deposit contract address */ function getDepositWithdrawCount(address _deposit) onlyOwner public view returns (uint) { require(_deposit != address(0)); WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; uint len = withdrawWalletList.length; return len; } /** * @dev get the withdraw wallet addresses list binding to the deposit contract address * * @param _deposit the deposit contract address * @param _indices the array of indices of the withdraw wallets */ function getDepositWithdrawList(address _deposit, uint[] _indices) onlyOwner public view returns (bytes32[], address[]) { require(_indices.length != 0); bytes32[] memory names = new bytes32[](_indices.length); address[] memory wallets = new address[](_indices.length); for (uint i = 0; i < _indices.length; i = i.add(1)) { WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[_indices[i]]; names[i] = wallet.name; wallets[i] = wallet.walletAddr; } return (names, wallets); } /** * @dev change the default withdraw wallet address binding to the deposit contract address * * @param _oldWallet the previous default withdraw wallet * @param _newWallet the new default withdraw wallet */ function changeDefaultWithdraw(address _oldWallet, address _newWallet) onlyOwner public returns (bool) { require(_newWallet != address(0)); address deposit = walletDeposits[_oldWallet]; DepositWithdraw deposWithdr = DepositWithdraw(deposit); require(deposWithdr.setWithdrawWallet(_newWallet)); WithdrawWallet[] storage withdrawWalletList = depositRepos[deposit].withdrawWallets; withdrawWalletList[0].walletAddr = _newWallet; emit ChangeDefaultWallet(_oldWallet, _newWallet); return true; } /** * @dev freeze the tokens in the deposit address * * @param _deposit the deposit address * @param _value the amount of tokens need to be frozen */ function freezeTokens(address _deposit, uint256 _value) onlyOwner public returns (bool) { require(_deposit != address(0)); frozenDeposits[_deposit] = true; depositRepos[_deposit].frozen = _value; emit FrozenTokens(_deposit, _value); return true; } /** * @dev withdraw the tokens from the deposit address with charge fee * * @param _deposit the deposit address * @param _time the timestamp the withdraw occurs * @param _value the amount of tokens need to be frozen */ function withdrawWithFee(address _deposit, uint256 _time, uint256 _value) onlyOwner public returns (bool) { require(_deposit != address(0)); uint256 _balance = tk.balanceOf(_deposit); require(_value <= _balance); // depositRepos[_deposit].balance = _balance; uint256 frozenAmount = depositRepos[_deposit].frozen; require(_value <= _balance.sub(frozenAmount)); DepositWithdraw deposWithdr = DepositWithdraw(_deposit); return (deposWithdr.withdrawTokenToDefault(address(tk), address(params), _time, _value, params.chargeFee(), params.chargeFeePool())); } /** * @dev check if the wallet name is not matching the expected wallet address * * @param _deposit the deposit address * @param _name the withdraw wallet name * @param _to the withdraw wallet address */ function checkWithdrawAddress(address _deposit, bytes32 _name, address _to) public view returns (bool, bool) { uint len = depositRepos[_deposit].withdrawWallets.length; for (uint i = 0; i < len; i = i.add(1)) { WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[i]; if (_name == wallet.name) { return(true, (_to == wallet.walletAddr)); } } return (false, true); } /** * @dev withdraw tokens, send tokens to target withdraw wallet * * @param _deposit the deposit address that will be withdraw from * @param _time the timestamp occur the withdraw record * @param _name the withdraw address alias name to verify * @param _to the address the token will be transfer to * @param _value the token transferred value * @param _check if we will check the value is valid or meet the limit condition */ function withdrawWithFee(address _deposit, uint256 _time, bytes32 _name, address _to, uint256 _value, bool _check) onlyOwner public returns (bool) { require(_deposit != address(0)); require(_to != address(0)); uint256 _balance = tk.balanceOf(_deposit); if (_check) { require(_value <= _balance); } uint256 available = _balance.sub(depositRepos[_deposit].frozen); if (_check) { require(_value <= available); } bool exist; bool correct; WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; (exist, correct) = checkWithdrawAddress(_deposit, _name, _to); if(!exist) { withdrawWalletList.push(WithdrawWallet(_name, _to)); } else if(!correct) { return false; } if (!_check && _value > available) { tk.transfer(_deposit, _value.sub(available)); _value = _value.sub(available); } DepositWithdraw deposWithdr = DepositWithdraw(_deposit); return (deposWithdr.withdrawToken(address(tk), address(params), _time, _to, _value, params.chargeFee(), params.chargeFeePool())); } } contract DRCWalletMgrParams is Claimable, Autonomy, Destructible { uint256 public singleWithdraw; // Max value of single withdraw uint256 public dayWithdraw; // Max value of one day of withdraw uint256 public monthWithdraw; // Max value of one month of withdraw uint256 public dayWithdrawCount; // Max number of withdraw counting uint256 public chargeFee; // the charge fee for withdraw address public chargeFeePool; // the address that will get the returned charge fees. function initialSingleWithdraw(uint256 _value) onlyOwner public { require(!init); singleWithdraw = _value; } function initialDayWithdraw(uint256 _value) onlyOwner public { require(!init); dayWithdraw = _value; } function initialDayWithdrawCount(uint256 _count) onlyOwner public { require(!init); dayWithdrawCount = _count; } function initialMonthWithdraw(uint256 _value) onlyOwner public { require(!init); monthWithdraw = _value; } function initialChargeFee(uint256 _value) onlyOwner public { require(!init); singleWithdraw = _value; } function initialChargeFeePool(address _pool) onlyOwner public { require(!init); chargeFeePool = _pool; } function setSingleWithdraw(uint256 _value) onlyCongress public { singleWithdraw = _value; } function setDayWithdraw(uint256 _value) onlyCongress public { dayWithdraw = _value; } function setDayWithdrawCount(uint256 _count) onlyCongress public { dayWithdrawCount = _count; } function setMonthWithdraw(uint256 _value) onlyCongress public { monthWithdraw = _value; } function setChargeFee(uint256 _value) onlyCongress public { singleWithdraw = _value; } function setChargeFeePool(address _pool) onlyOwner public { chargeFeePool = _pool; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); }
TOD1
/* ==================================================================== */ /* Copyright (c) 2018 The ether.online Project. All rights reserved. /* /* https://ether.online The first RPG game of blockchain /* /* authors [email protected] /* [email protected] /* ==================================================================== */ pragma solidity ^0.4.20; /// @title ERC-165 Standard Interface Detection /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md contract ERC721 is ERC165 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function approve(address _approved, uint256 _tokenId) external; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } contract AccessAdmin { bool public isPaused = false; address public addrAdmin; event AdminTransferred(address indexed preAdmin, address indexed newAdmin); function AccessAdmin() public { addrAdmin = msg.sender; } modifier onlyAdmin() { require(msg.sender == addrAdmin); _; } modifier whenNotPaused() { require(!isPaused); _; } modifier whenPaused { require(isPaused); _; } function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); AdminTransferred(addrAdmin, _newAdmin); addrAdmin = _newAdmin; } function doPause() external onlyAdmin whenNotPaused { isPaused = true; } function doUnpause() external onlyAdmin whenPaused { isPaused = false; } } contract AccessService is AccessAdmin { address public addrService; address public addrFinance; modifier onlyService() { require(msg.sender == addrService); _; } modifier onlyFinance() { require(msg.sender == addrFinance); _; } function setService(address _newService) external { require(msg.sender == addrService || msg.sender == addrAdmin); require(_newService != address(0)); addrService = _newService; } function setFinance(address _newFinance) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_newFinance != address(0)); addrFinance = _newFinance; } function withdraw(address _target, uint256 _amount) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_amount > 0); address receiver = _target == address(0) ? addrFinance : _target; uint256 balance = this.balance; if (_amount < balance) { receiver.transfer(_amount); } else { receiver.transfer(this.balance); } } } interface IDataMining { function getRecommender(address _target) external view returns(address); function subFreeMineral(address _target) external returns(bool); } interface IDataEquip { function isEquiped(address _target, uint256 _tokenId) external view returns(bool); function isEquipedAny2(address _target, uint256 _tokenId1, uint256 _tokenId2) external view returns(bool); function isEquipedAny3(address _target, uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool); } interface IDataAuction { function isOnSaleAny2(uint256 _tokenId1, uint256 _tokenId2) external view returns(bool); function isOnSaleAny3(uint256 _tokenId1, uint256 _tokenId2, uint256 _tokenId3) external view returns(bool); } interface IBitGuildToken { function transfer(address _to, uint256 _value) external; function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external; function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool); function balanceOf(address _from) external view returns(uint256); } contract Random { uint256 _seed; function _rand() internal returns (uint256) { _seed = uint256(keccak256(_seed, block.blockhash(block.number - 1), block.coinbase, block.difficulty)); return _seed; } function _randBySeed(uint256 _outSeed) internal view returns (uint256) { return uint256(keccak256(_outSeed, block.blockhash(block.number - 1), block.coinbase, block.difficulty)); } } /** * @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; } } contract WarToken is ERC721, AccessAdmin { /// @dev The equipment info struct Fashion { uint16 protoId; // 0 Equipment ID uint16 quality; // 1 Rarity: 1 Coarse/2 Good/3 Rare/4 Epic/5 Legendary uint16 pos; // 2 Slots: 1 Weapon/2 Hat/3 Cloth/4 Pant/5 Shoes/9 Pets uint16 health; // 3 Health uint16 atkMin; // 4 Min attack uint16 atkMax; // 5 Max attack uint16 defence; // 6 Defennse uint16 crit; // 7 Critical rate uint16 isPercent; // 8 Attr value type uint16 attrExt1; // 9 future stat 1 uint16 attrExt2; // 10 future stat 2 uint16 attrExt3; // 11 future stat 3 } /// @dev All equipments tokenArray (not exceeding 2^32-1) Fashion[] public fashionArray; /// @dev Amount of tokens destroyed uint256 destroyFashionCount; /// @dev Equipment token ID vs owner address mapping (uint256 => address) fashionIdToOwner; /// @dev Equipments owner by the owner (array) mapping (address => uint256[]) ownerToFashionArray; /// @dev Equipment token ID search in owner array mapping (uint256 => uint256) fashionIdToOwnerIndex; /// @dev The authorized address for each WAR mapping (uint256 => address) fashionIdToApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) operatorToApprovals; /// @dev Trust contract mapping (address => bool) actionContracts; function setActionContract(address _actionAddr, bool _useful) external onlyAdmin { actionContracts[_actionAddr] = _useful; } function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) { return actionContracts[_actionAddr]; } /// @dev This emits when the approved address for an WAR is changed or reaffirmed. event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @dev This emits when the equipment ownership changed event Transfer(address indexed from, address indexed to, uint256 tokenId); /// @dev This emits when the equipment created event CreateFashion(address indexed owner, uint256 tokenId, uint16 protoId, uint16 quality, uint16 pos, uint16 createType); /// @dev This emits when the equipment's attributes changed event ChangeFashion(address indexed owner, uint256 tokenId, uint16 changeType); /// @dev This emits when the equipment destroyed event DeleteFashion(address indexed owner, uint256 tokenId, uint16 deleteType); function WarToken() public { addrAdmin = msg.sender; fashionArray.length += 1; } // modifier /// @dev Check if token ID is valid modifier isValidToken(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= fashionArray.length); require(fashionIdToOwner[_tokenId] != address(0)); _; } modifier canTransfer(uint256 _tokenId) { address owner = fashionIdToOwner[_tokenId]; require(msg.sender == owner || msg.sender == fashionIdToApprovals[_tokenId] || operatorToApprovals[owner][msg.sender]); _; } // ERC721 function supportsInterface(bytes4 _interfaceId) external view returns(bool) { // ERC165 || ERC721 || ERC165^ERC721 return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff); } function name() public pure returns(string) { return "WAR Token"; } function symbol() public pure returns(string) { return "WAR"; } /// @dev Search for token quantity address /// @param _owner Address that needs to be searched /// @return Returns token quantity function balanceOf(address _owner) external view returns(uint256) { require(_owner != address(0)); return ownerToFashionArray[_owner].length; } /// @dev Find the owner of an WAR /// @param _tokenId The tokenId of WAR /// @return Give The address of the owner of this WAR function ownerOf(uint256 _tokenId) external view /*isValidToken(_tokenId)*/ returns (address owner) { return fashionIdToOwner[_tokenId]; } /// @dev Transfers the ownership of an WAR from one address to another address /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, data); } /// @dev Transfers the ownership of an WAR from one address to another address /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @dev Transfer ownership of an WAR, '_to' must be a vaild address, or the WAR will lost /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused isValidToken(_tokenId) canTransfer(_tokenId) { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner == _from); _transfer(_from, _to, _tokenId); } /// @dev Set or reaffirm the approved address for an WAR /// @param _approved The new approved WAR controller /// @param _tokenId The WAR to approve function approve(address _approved, uint256 _tokenId) external whenNotPaused { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(msg.sender == owner || operatorToApprovals[owner][msg.sender]); fashionIdToApprovals[_tokenId] = _approved; Approval(owner, _approved, _tokenId); } /// @dev Enable or disable approval for a third party ("operator") to manage all your asset. /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external whenNotPaused { operatorToApprovals[msg.sender][_operator] = _approved; ApprovalForAll(msg.sender, _operator, _approved); } /// @dev Get the approved address for a single WAR /// @param _tokenId The WAR to find the approved address for /// @return The approved address for this WAR, or the zero address if there is none function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) { return fashionIdToApprovals[_tokenId]; } /// @dev Query if an address is an authorized operator for another address /// @param _owner The address that owns the WARs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorToApprovals[_owner][_operator]; } /// @dev Count WARs tracked by this contract /// @return A count of valid WARs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256) { return fashionArray.length - destroyFashionCount - 1; } /// @dev Do the real transfer with out any condition checking /// @param _from The old owner of this WAR(If created: 0x0) /// @param _to The new owner of this WAR /// @param _tokenId The tokenId of the WAR function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)) { uint256 indexFrom = fashionIdToOwnerIndex[_tokenId]; uint256[] storage fsArray = ownerToFashionArray[_from]; require(fsArray[indexFrom] == _tokenId); // If the WAR is not the element of array, change it to with the last if (indexFrom != fsArray.length - 1) { uint256 lastTokenId = fsArray[fsArray.length - 1]; fsArray[indexFrom] = lastTokenId; fashionIdToOwnerIndex[lastTokenId] = indexFrom; } fsArray.length -= 1; if (fashionIdToApprovals[_tokenId] != address(0)) { delete fashionIdToApprovals[_tokenId]; } } // Give the WAR to '_to' fashionIdToOwner[_tokenId] = _to; ownerToFashionArray[_to].push(_tokenId); fashionIdToOwnerIndex[_tokenId] = ownerToFashionArray[_to].length - 1; Transfer(_from != address(0) ? _from : this, _to, _tokenId); } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) internal isValidToken(_tokenId) canTransfer(_tokenId) { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner == _from); _transfer(_from, _to, _tokenId); // Do the callback after everything is done to avoid reentrancy attack uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); // bytes4(keccak256("onERC721Received(address,uint256,bytes)")) = 0xf0b9e5ba; require(retval == 0xf0b9e5ba); } //---------------------------------------------------------------------------------------------------------- /// @dev Equipment creation /// @param _owner Owner of the equipment created /// @param _attrs Attributes of the equipment created /// @return Token ID of the equipment created function createFashion(address _owner, uint16[9] _attrs, uint16 _createType) external whenNotPaused returns(uint256) { require(actionContracts[msg.sender]); require(_owner != address(0)); uint256 newFashionId = fashionArray.length; require(newFashionId < 4294967296); fashionArray.length += 1; Fashion storage fs = fashionArray[newFashionId]; fs.protoId = _attrs[0]; fs.quality = _attrs[1]; fs.pos = _attrs[2]; if (_attrs[3] != 0) { fs.health = _attrs[3]; } if (_attrs[4] != 0) { fs.atkMin = _attrs[4]; fs.atkMax = _attrs[5]; } if (_attrs[6] != 0) { fs.defence = _attrs[6]; } if (_attrs[7] != 0) { fs.crit = _attrs[7]; } if (_attrs[8] != 0) { fs.isPercent = _attrs[8]; } _transfer(0, _owner, newFashionId); CreateFashion(_owner, newFashionId, _attrs[0], _attrs[1], _attrs[2], _createType); return newFashionId; } /// @dev One specific attribute of the equipment modified function _changeAttrByIndex(Fashion storage _fs, uint16 _index, uint16 _val) internal { if (_index == 3) { _fs.health = _val; } else if(_index == 4) { _fs.atkMin = _val; } else if(_index == 5) { _fs.atkMax = _val; } else if(_index == 6) { _fs.defence = _val; } else if(_index == 7) { _fs.crit = _val; } else if(_index == 9) { _fs.attrExt1 = _val; } else if(_index == 10) { _fs.attrExt2 = _val; } else if(_index == 11) { _fs.attrExt3 = _val; } } /// @dev Equiment attributes modified (max 4 stats modified) /// @param _tokenId Equipment Token ID /// @param _idxArray Stats order that must be modified /// @param _params Stat value that must be modified /// @param _changeType Modification type such as enhance, socket, etc. function changeFashionAttr(uint256 _tokenId, uint16[4] _idxArray, uint16[4] _params, uint16 _changeType) external whenNotPaused isValidToken(_tokenId) { require(actionContracts[msg.sender]); Fashion storage fs = fashionArray[_tokenId]; if (_idxArray[0] > 0) { _changeAttrByIndex(fs, _idxArray[0], _params[0]); } if (_idxArray[1] > 0) { _changeAttrByIndex(fs, _idxArray[1], _params[1]); } if (_idxArray[2] > 0) { _changeAttrByIndex(fs, _idxArray[2], _params[2]); } if (_idxArray[3] > 0) { _changeAttrByIndex(fs, _idxArray[3], _params[3]); } ChangeFashion(fashionIdToOwner[_tokenId], _tokenId, _changeType); } /// @dev Equipment destruction /// @param _tokenId Equipment Token ID /// @param _deleteType Destruction type, such as craft function destroyFashion(uint256 _tokenId, uint16 _deleteType) external whenNotPaused isValidToken(_tokenId) { require(actionContracts[msg.sender]); address _from = fashionIdToOwner[_tokenId]; uint256 indexFrom = fashionIdToOwnerIndex[_tokenId]; uint256[] storage fsArray = ownerToFashionArray[_from]; require(fsArray[indexFrom] == _tokenId); if (indexFrom != fsArray.length - 1) { uint256 lastTokenId = fsArray[fsArray.length - 1]; fsArray[indexFrom] = lastTokenId; fashionIdToOwnerIndex[lastTokenId] = indexFrom; } fsArray.length -= 1; fashionIdToOwner[_tokenId] = address(0); delete fashionIdToOwnerIndex[_tokenId]; destroyFashionCount += 1; Transfer(_from, 0, _tokenId); DeleteFashion(_from, _tokenId, _deleteType); } /// @dev Safe transfer by trust contracts function safeTransferByContract(uint256 _tokenId, address _to) external whenNotPaused { require(actionContracts[msg.sender]); require(_tokenId >= 1 && _tokenId <= fashionArray.length); address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner != _to); _transfer(owner, _to, _tokenId); } //---------------------------------------------------------------------------------------------------------- /// @dev Get fashion attrs by tokenId function getFashion(uint256 _tokenId) external view isValidToken(_tokenId) returns (uint16[12] datas) { Fashion storage fs = fashionArray[_tokenId]; datas[0] = fs.protoId; datas[1] = fs.quality; datas[2] = fs.pos; datas[3] = fs.health; datas[4] = fs.atkMin; datas[5] = fs.atkMax; datas[6] = fs.defence; datas[7] = fs.crit; datas[8] = fs.isPercent; datas[9] = fs.attrExt1; datas[10] = fs.attrExt2; datas[11] = fs.attrExt3; } /// @dev Get tokenIds and flags by owner function getOwnFashions(address _owner) external view returns(uint256[] tokens, uint32[] flags) { require(_owner != address(0)); uint256[] storage fsArray = ownerToFashionArray[_owner]; uint256 length = fsArray.length; tokens = new uint256[](length); flags = new uint32[](length); for (uint256 i = 0; i < length; ++i) { tokens[i] = fsArray[i]; Fashion storage fs = fashionArray[fsArray[i]]; flags[i] = uint32(uint32(fs.protoId) * 100 + uint32(fs.quality) * 10 + fs.pos); } } /// @dev WAR token info returned based on Token ID transfered (64 at most) function getFashionsAttrs(uint256[] _tokens) external view returns(uint16[] attrs) { uint256 length = _tokens.length; require(length <= 64); attrs = new uint16[](length * 11); uint256 tokenId; uint256 index; for (uint256 i = 0; i < length; ++i) { tokenId = _tokens[i]; if (fashionIdToOwner[tokenId] != address(0)) { index = i * 11; Fashion storage fs = fashionArray[tokenId]; attrs[index] = fs.health; attrs[index + 1] = fs.atkMin; attrs[index + 2] = fs.atkMax; attrs[index + 3] = fs.defence; attrs[index + 4] = fs.crit; attrs[index + 5] = fs.isPercent; attrs[index + 6] = fs.attrExt1; attrs[index + 7] = fs.attrExt2; attrs[index + 8] = fs.attrExt3; } } } } contract ActionMiningPlat is Random, AccessService { using SafeMath for uint256; event MiningOrderPlatCreated(uint256 indexed index, address indexed miner, uint64 chestCnt); event MiningPlatResolved(uint256 indexed index, address indexed miner, uint64 chestCnt); struct MiningOrder { address miner; uint64 chestCnt; uint64 tmCreate; uint64 tmResolve; } /// @dev Max fashion suit id uint16 maxProtoId; /// @dev If the recommender can get reward bool isRecommendOpen; /// @dev WarToken(NFT) contract address WarToken public tokenContract; /// @dev DataMining contract address IDataMining public dataContract; /// @dev mining order array MiningOrder[] public ordersArray; /// @dev suit count mapping (uint16 => uint256) public protoIdToCount; /// @dev BitGuildToken address IBitGuildToken public bitGuildContract; /// @dev mining Price of PLAT uint256 public miningOnePlat = 600000000000000000000; uint256 public miningThreePlat = 1800000000000000000000; uint256 public miningFivePlat = 2850000000000000000000; uint256 public miningTenPlat = 5400000000000000000000; function ActionMiningPlat(address _nftAddr, uint16 _maxProtoId, address _platAddr) public { addrAdmin = msg.sender; addrService = msg.sender; addrFinance = msg.sender; tokenContract = WarToken(_nftAddr); maxProtoId = _maxProtoId; MiningOrder memory order = MiningOrder(0, 0, 1, 1); ordersArray.push(order); bitGuildContract = IBitGuildToken(_platAddr); } function() external payable { } function getPlatBalance() external view returns(uint256) { return bitGuildContract.balanceOf(this); } function withdrawPlat() external { require(msg.sender == addrFinance || msg.sender == addrAdmin); uint256 balance = bitGuildContract.balanceOf(this); require(balance > 0); bitGuildContract.transfer(addrFinance, balance); } function getOrderCount() external view returns(uint256) { return ordersArray.length - 1; } function setDataMining(address _addr) external onlyAdmin { require(_addr != address(0)); dataContract = IDataMining(_addr); } function setMaxProtoId(uint16 _maxProtoId) external onlyAdmin { require(_maxProtoId > 0 && _maxProtoId < 10000); require(_maxProtoId != maxProtoId); maxProtoId = _maxProtoId; } function setRecommendStatus(bool _isOpen) external onlyAdmin { require(_isOpen != isRecommendOpen); isRecommendOpen = _isOpen; } function setFashionSuitCount(uint16 _protoId, uint256 _cnt) external onlyAdmin { require(_protoId > 0 && _protoId <= maxProtoId); require(_cnt > 0 && _cnt <= 5); require(protoIdToCount[_protoId] != _cnt); protoIdToCount[_protoId] = _cnt; } function changePlatPrice(uint32 miningType, uint256 price) external onlyAdmin { require(price > 0 && price < 100000); uint256 newPrice = price * 1000000000000000000; if (miningType == 1) { miningOnePlat = newPrice; } else if (miningType == 3) { miningThreePlat = newPrice; } else if (miningType == 5) { miningFivePlat = newPrice; } else if (miningType == 10) { miningTenPlat = newPrice; } else { require(false); } } function _getFashionParam(uint256 _seed) internal view returns(uint16[9] attrs) { uint256 curSeed = _seed; // quality uint256 rdm = curSeed % 10000; uint16 qtyParam; if (rdm < 6900) { attrs[1] = 1; qtyParam = 0; } else if (rdm < 8700) { attrs[1] = 2; qtyParam = 1; } else if (rdm < 9600) { attrs[1] = 3; qtyParam = 2; } else if (rdm < 9900) { attrs[1] = 4; qtyParam = 4; } else { attrs[1] = 5; qtyParam = 6; } // protoId curSeed /= 10000; rdm = ((curSeed % 10000) / (9999 / maxProtoId)) + 1; attrs[0] = uint16(rdm <= maxProtoId ? rdm : maxProtoId); // pos curSeed /= 10000; uint256 tmpVal = protoIdToCount[attrs[0]]; if (tmpVal == 0) { tmpVal = 5; } rdm = ((curSeed % 10000) / (9999 / tmpVal)) + 1; uint16 pos = uint16(rdm <= tmpVal ? rdm : tmpVal); attrs[2] = pos; rdm = attrs[0] % 3; curSeed /= 10000; tmpVal = (curSeed % 10000) % 21 + 90; if (rdm == 0) { if (pos == 1) { uint256 attr = (200 + qtyParam * 200) * tmpVal / 100; // +atk attrs[4] = uint16(attr * 40 / 100); attrs[5] = uint16(attr * 160 / 100); } else if (pos == 2) { attrs[6] = uint16((40 + qtyParam * 40) * tmpVal / 100); // +def } else if (pos == 3) { attrs[3] = uint16((600 + qtyParam * 600) * tmpVal / 100); // +hp } else if (pos == 4) { attrs[6] = uint16((60 + qtyParam * 60) * tmpVal / 100); // +def } else { attrs[3] = uint16((400 + qtyParam * 400) * tmpVal / 100); // +hp } } else if (rdm == 1) { if (pos == 1) { uint256 attr2 = (190 + qtyParam * 190) * tmpVal / 100; // +atk attrs[4] = uint16(attr2 * 50 / 100); attrs[5] = uint16(attr2 * 150 / 100); } else if (pos == 2) { attrs[6] = uint16((42 + qtyParam * 42) * tmpVal / 100); // +def } else if (pos == 3) { attrs[3] = uint16((630 + qtyParam * 630) * tmpVal / 100); // +hp } else if (pos == 4) { attrs[6] = uint16((63 + qtyParam * 63) * tmpVal / 100); // +def } else { attrs[3] = uint16((420 + qtyParam * 420) * tmpVal / 100); // +hp } } else { if (pos == 1) { uint256 attr3 = (210 + qtyParam * 210) * tmpVal / 100; // +atk attrs[4] = uint16(attr3 * 30 / 100); attrs[5] = uint16(attr3 * 170 / 100); } else if (pos == 2) { attrs[6] = uint16((38 + qtyParam * 38) * tmpVal / 100); // +def } else if (pos == 3) { attrs[3] = uint16((570 + qtyParam * 570) * tmpVal / 100); // +hp } else if (pos == 4) { attrs[6] = uint16((57 + qtyParam * 57) * tmpVal / 100); // +def } else { attrs[3] = uint16((380 + qtyParam * 380) * tmpVal / 100); // +hp } } attrs[8] = 0; } function _addOrder(address _miner, uint64 _chestCnt) internal { uint64 newOrderId = uint64(ordersArray.length); ordersArray.length += 1; MiningOrder storage order = ordersArray[newOrderId]; order.miner = _miner; order.chestCnt = _chestCnt; order.tmCreate = uint64(block.timestamp); MiningOrderPlatCreated(newOrderId, _miner, _chestCnt); } function _transferHelper(address _player, uint256 _platVal) private { if (isRecommendOpen) { address recommender = dataContract.getRecommender(_player); if (recommender != address(0)) { uint256 rVal = _platVal.div(10); if (rVal > 0) { bitGuildContract.transfer(recommender, rVal); } } } } function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData) external whenNotPaused { require(msg.sender == address(bitGuildContract)); require(_extraData.length == 1); uint32 miningType = uint32(_extraData[0]); if (miningType == 0) { require(_value == miningOnePlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _miningOneSelf(_sender); } else if (miningType == 10) { require(_value == miningTenPlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _addOrder(_sender, 10); } else if (miningType == 3) { require(_value == miningThreePlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _addOrder(_sender, 3); } else if (miningType == 5) { require(_value == miningFivePlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _addOrder(_sender, 5); } else if (miningType == 1) { require(_value == miningOnePlat); require(bitGuildContract.transferFrom(_sender, address(this), _value)); _addOrder(_sender, 1); } else { require(false); } _transferHelper(_sender, _value); } function _miningOneSelf(address _sender) internal { uint256 seed = _rand(); uint16[9] memory attrs = _getFashionParam(seed); tokenContract.createFashion(_sender, attrs, 6); MiningPlatResolved(0, _sender, 1); } function miningResolve(uint256 _orderIndex, uint256 _seed) external onlyService { require(_orderIndex > 0 && _orderIndex < ordersArray.length); MiningOrder storage order = ordersArray[_orderIndex]; require(order.tmResolve == 0); address miner = order.miner; require(miner != address(0)); uint64 chestCnt = order.chestCnt; require(chestCnt >= 1 && chestCnt <= 10); uint256 rdm = _seed; uint16[9] memory attrs; for (uint64 i = 0; i < chestCnt; ++i) { rdm = _randBySeed(rdm); attrs = _getFashionParam(rdm); tokenContract.createFashion(miner, attrs, 6); } order.tmResolve = uint64(block.timestamp); MiningPlatResolved(_orderIndex, miner, chestCnt); } }
TOD1
pragma solidity ^0.4.20; contract ENIGMA { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>3 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function SetGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
TOD1
pragma solidity ^0.4.2; contract CChain { //Model User struct User { int8 gifters; uint id; uint lineNo; bool in_queue; string uid; address eth_address; // bool newPayer; } //Store User User[] userStore; //Fetch User mapping(address => User) public users; mapping(uint => address) public intUsers; //Store User Count uint public userCount; //pay price //uint price = 0.10 ether; //contract fee //uint contract_price = 0.025 ether; uint gift = 0.30 ether; uint public total_price = 0.125 ether; //my own address public iown; uint public currentlyInLine; uint public lineCount; //Constructor constructor() public{ iown = msg.sender; currentlyInLine = 0; lineCount = 0; } //add User to Contract function addUser(string _user_id, address _user_address) private { require(users[_user_address].id == 0); userCount++; userStore.length++; User storage u = userStore[userStore.length - 1]; u.id = userCount; u.uid = _user_id; u.eth_address = _user_address; u.in_queue = false; u.gifters = 0; users[_user_address] = u; //intUsers[userCount] = _user_address; //checkGifters(); } //Pay to get in line function getInLine(string _user_id, address _user_address) public payable returns (bool) { require(msg.value >= total_price); require(users[_user_address].in_queue == false); if(users[_user_address].id == 0) { addUser(_user_id, _user_address); } lineCount++; User storage u = users[_user_address]; u.in_queue = true; u.lineNo = lineCount; intUsers[lineCount] = _user_address; checkGifters(); return true; } function checkGifters() private { if(currentlyInLine == 0){ currentlyInLine = 1; } else{ address add = intUsers[currentlyInLine]; User storage u = users[add]; u.gifters++; if(u.gifters == 3 && u.in_queue == true){ u.in_queue = false; currentlyInLine++; } } } //read your gifter function getMyGifters(address _user_address) external view returns (int8) { return users[_user_address].gifters; } //user withdraw function getGifted(address _user_address) external { require(users[_user_address].id != 0); require(users[_user_address].gifters == 3); if(users[_user_address].id != 0 && users[_user_address].gifters == 3){ _user_address.transfer(gift); User storage u = users[_user_address]; u.gifters = 0; } } //admin function withdraw() external{ require(msg.sender == iown); iown.transfer(address(this).balance); } function withdrawAmount(uint amount) external{ require(msg.sender == iown); iown.transfer(amount); } function getThisBalance() external view returns (uint) { return address(this).balance; } }
TOD1
pragma solidity ^0.4.23; library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } } library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; emit OwnershipTransferred(owner, newOwner); } } contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 public constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require (ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require (isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @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]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner 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; } function isOwnerOf(address _owner, uint256 _tokenId) public view returns (bool) { address owner = ownerOf(_tokenId); return owner == _owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev 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 * @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) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev 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 * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev 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 canTransfer(_tokenId) { require (_from != address(0)); require (_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev 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. * @dev 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 canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev 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. * @dev 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 _data) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require (checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @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); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (_spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender)); } /** * @dev Internal function to mint a new token * @dev 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 by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { //require (_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require (ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { // require (tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { require (ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev 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 whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 public constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received(address, address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } /** * @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://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_ = "CryptoFlowers"; // Token symbol string internal symbol_ = "CF"; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @notice The user/developper needs to add the tokenID, in the end of URL, to * use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID> * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); string memory infoUrl; infoUrl = strConcat('https://cryptoflowers.io/v/', uint2str(_tokenId)); return infoUrl; } /** * @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 totalSupply() public view returns (uint256) { return allTokens.length - 1; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev 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 <= totalSupply()); return allTokens[_index]; } /** * @dev Internal function to add a token ID to the list of a given address * @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 addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Internal function to mint a new token * @dev 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 by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @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); // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; /* bytes4(keccak256('supportsInterface(bytes4)')); */ bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63; /* bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('tokenByIndex(uint256)')); */ bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f; /* bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('tokenURI(uint256)')); */ bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; /* bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('getApproved(uint256)')) ^ bytes4(keccak256('setApprovalForAll(address,bool)')) ^ bytes4(keccak256('isApprovedForAll(address,address)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')); */ bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79; /* bytes4(keccak256('exists(uint256)')); */ /** * @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). * @dev Returns true for any standardized interfaces implemented by this contract. * @param _interfaceID bytes4 the interface to check for * @return true for any standardized interfaces implemented by this contract. */ function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceSignature_ERC721Enumerable) || (_interfaceID == InterfaceSignature_ERC721Metadata)); } function implementsERC721() public pure returns (bool) { return true; } } contract GenomeInterface { function isGenome() public pure returns (bool); function mixGenes(uint256 genes1, uint256 genes2) public returns (uint256); } contract FlowerAdminAccess { address public rootAddress; address public adminAddress; event ContractUpgrade(address newContract); address public gen0SellerAddress; address public giftHolderAddress; bool public stopped = false; modifier onlyRoot() { require(msg.sender == rootAddress); _; } modifier onlyAdmin() { require(msg.sender == adminAddress); _; } modifier onlyAdministrator() { require(msg.sender == rootAddress || msg.sender == adminAddress); _; } function setRoot(address _newRoot) external onlyAdministrator { require(_newRoot != address(0)); rootAddress = _newRoot; } function setAdmin(address _newAdmin) external onlyRoot { require(_newAdmin != address(0)); adminAddress = _newAdmin; } modifier whenNotStopped() { require(!stopped); _; } modifier whenStopped { require(stopped); _; } function setStop() public onlyAdministrator whenNotStopped { stopped = true; } function setStart() public onlyAdministrator whenStopped { stopped = false; } } contract FlowerBase is ERC721Token { struct Flower { uint256 genes; uint64 birthTime; uint64 cooldownEndBlock; uint32 matronId; uint32 sireId; uint16 cooldownIndex; uint16 generation; } Flower[] flowers; mapping (uint256 => uint256) genomeFlowerIds; // Сooldown duration uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; event Birth(address owner, uint256 flowerId, uint256 matronId, uint256 sireId, uint256 genes); event Transfer(address from, address to, uint256 tokenId); event Money(address from, string actionType, uint256 sum, uint256 cut, uint256 tokenId, uint256 blockNumber); function _createFlower(uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); require(checkUnique(_genes)); uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Flower memory _flower = Flower({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newFlowerId = flowers.push(_flower) - 1; require(newFlowerId == uint256(uint32(newFlowerId))); genomeFlowerIds[_genes] = newFlowerId; emit Birth(_owner, newFlowerId, uint256(_flower.matronId), uint256(_flower.sireId), _flower.genes); _mint(_owner, newFlowerId); return newFlowerId; } function checkUnique(uint256 _genome) public view returns (bool) { uint256 _flowerId = uint256(genomeFlowerIds[_genome]); return !(_flowerId > 0); } } contract FlowerOwnership is FlowerBase, FlowerAdminAccess { SaleClockAuction public saleAuction; BreedingClockAuction public breedingAuction; uint256 public secondsPerBlock = 15; function setSecondsPerBlock(uint256 secs) external onlyAdministrator { require(secs < cooldowns[0]); secondsPerBlock = secs; } } contract ClockAuctionBase { struct Auction { address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; } ERC721Token public nonFungibleContract; uint256 public ownerCut; mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); event Money(address from, string actionType, uint256 sum, uint256 cut, uint256 tokenId, uint256 blockNumber); function isOwnerOf(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.transferFrom(_owner, this, _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.transferFrom(this, _receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated(uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration)); } function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } function _bid(uint256 _tokenId, uint256 _bidAmount, address _sender) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); emit Money(_sender, "AuctionSuccessful", price, auctioneerCut, _tokenId, block.number); } uint256 bidExcess = _bidAmount - price; _sender.transfer(bidExcess); emit AuctionSuccessful(_tokenId, price, _sender); return price; } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0 && _auction.startedAt < now); } function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice(_auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed); } function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256) { return uint256(_price * ownerCut / 10000); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } contract ClockAuction is Pausable, ClockAuctionBase { bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd); constructor(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721Token candidateContract = ERC721Token(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require(msg.sender == owner || msg.sender == nftAddress); owner.transfer(address(this).balance); } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller, uint64 _startAt) external whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(isOwnerOf(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); uint64 startAt = _startAt; if (_startAt == 0) { startAt = uint64(now); } Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(startAt) ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId, address _sender) external payable whenNotPaused { _bid(_tokenId, msg.value, _sender); _transfer(_sender, _tokenId); } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionByAdmin(uint256 _tokenId) onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getAuction(uint256 _tokenId) external view returns (address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return (auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256){ Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } // TMP function getContractBalance() onlyOwner external view returns (uint256) { return address(this).balance; } } contract BreedingClockAuction is ClockAuction { bool public isBreedingClockAuction = true; constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function bid(uint256 _tokenId, address _sender) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; _bid(_tokenId, msg.value, _sender); _transfer(seller, _tokenId); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller, uint64 _startAt) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 startAt = _startAt; if (_startAt == 0) { startAt = uint64(now); } Auction memory auction = Auction(_seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(startAt)); _addAuction(_tokenId, auction); } } contract SaleClockAuction is ClockAuction { bool public isSaleClockAuction = true; uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} address public gen0SellerAddress; function setGen0SellerAddress(address _newAddress) external { require(msg.sender == address(nonFungibleContract)); gen0SellerAddress = _newAddress; } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller, uint64 _startAt) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 startAt = _startAt; if (_startAt == 0) { startAt = uint64(now); } Auction memory auction = Auction(_seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(startAt)); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value, msg.sender); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(gen0SellerAddress)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function bidGift(uint256 _tokenId, address _to) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value, msg.sender); _transfer(_to, _tokenId); // If not a gen0 auction, exit if (seller == address(gen0SellerAddress)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } function computeCut(uint256 _price) public view returns (uint256) { return _computeCut(_price); } function getSeller(uint256 _tokenId) public view returns (address) { return address(tokenIdToAuction[_tokenId].seller); } } // Flowers crossing contract FlowerBreeding is FlowerOwnership { // Fee for breeding uint256 public autoBirthFee = 2 finney; uint256 public giftFee = 2 finney; GenomeInterface public geneScience; // Set Genome contract address function setGenomeContractAddress(address _address) external onlyAdministrator { geneScience = GenomeInterface(_address); } function _isReadyToAction(Flower _flower) internal view returns (bool) { return _flower.cooldownEndBlock <= uint64(block.number); } function isReadyToAction(uint256 _flowerId) public view returns (bool) { require(_flowerId > 0); Flower storage flower = flowers[_flowerId]; return _isReadyToAction(flower); } function _setCooldown(Flower storage _flower) internal { _flower.cooldownEndBlock = uint64((cooldowns[_flower.cooldownIndex]/secondsPerBlock) + block.number); if (_flower.cooldownIndex < 13) { _flower.cooldownIndex += 1; } } function setAutoBirthFee(uint256 val) external onlyAdministrator { autoBirthFee = val; } function setGiftFee(uint256 _fee) external onlyAdministrator { giftFee = _fee; } // Check if a given sire and matron are a valid crossing pair function _isValidPair(Flower storage _matron, uint256 _matronId, Flower storage _sire, uint256 _sireId) private view returns(bool) { if (_matronId == _sireId) { return false; } // Generation zero can crossing if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Do not crossing with it parrents if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // Can't crossing with brothers and sisters if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } return true; } function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns (bool) { return _canBreedWith(_matronId, _sireId); } function _canBreedWith(uint256 _matronId, uint256 _sireId) internal view returns (bool) { require(_matronId > 0); require(_sireId > 0); Flower storage matron = flowers[_matronId]; Flower storage sire = flowers[_sireId]; return _isValidPair(matron, _matronId, sire, _sireId); } function _born(uint256 _matronId, uint256 _sireId) internal { Flower storage sire = flowers[_sireId]; Flower storage matron = flowers[_matronId]; uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes); address owner = ownerOf(_matronId); uint256 flowerId = _createFlower(_matronId, _sireId, parentGen + 1, childGenes, owner); Flower storage child = flowers[flowerId]; _setCooldown(sire); _setCooldown(matron); _setCooldown(child); } // Crossing two of owner flowers function breedOwn(uint256 _matronId, uint256 _sireId) external payable whenNotStopped { require(msg.value >= autoBirthFee); require(isOwnerOf(msg.sender, _matronId)); require(isOwnerOf(msg.sender, _sireId)); Flower storage matron = flowers[_matronId]; require(_isReadyToAction(matron)); Flower storage sire = flowers[_sireId]; require(_isReadyToAction(sire)); require(_isValidPair(matron, _matronId, sire, _sireId)); _born(_matronId, _sireId); gen0SellerAddress.transfer(autoBirthFee); emit Money(msg.sender, "BirthFee-own", autoBirthFee, autoBirthFee, _sireId, block.number); } } // Handles creating auctions for sale and siring contract FlowerAuction is FlowerBreeding { // Set sale auction contract address function setSaleAuctionAddress(address _address) external onlyAdministrator { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } // Set siring auction contract address function setBreedingAuctionAddress(address _address) external onlyAdministrator { BreedingClockAuction candidateContract = BreedingClockAuction(_address); require(candidateContract.isBreedingClockAuction()); breedingAuction = candidateContract; } // Flower sale auction function createSaleAuction(uint256 _flowerId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external whenNotStopped { require(isOwnerOf(msg.sender, _flowerId)); require(isReadyToAction(_flowerId)); approve(saleAuction, _flowerId); saleAuction.createAuction(_flowerId, _startingPrice, _endingPrice, _duration, msg.sender, 0); } // Create siring auction function createBreedingAuction(uint256 _flowerId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external whenNotStopped { require(isOwnerOf(msg.sender, _flowerId)); require(isReadyToAction(_flowerId)); approve(breedingAuction, _flowerId); breedingAuction.createAuction(_flowerId, _startingPrice, _endingPrice, _duration, msg.sender, 0); } // Siring auction complete function bidOnBreedingAuction(uint256 _sireId, uint256 _matronId) external payable whenNotStopped { require(isOwnerOf(msg.sender, _matronId)); require(isReadyToAction(_matronId)); require(isReadyToAction(_sireId)); require(_canBreedWith(_matronId, _sireId)); uint256 currentPrice = breedingAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. breedingAuction.bid.value(msg.value - autoBirthFee)(_sireId, msg.sender); _born(uint32(_matronId), uint32(_sireId)); gen0SellerAddress.transfer(autoBirthFee); emit Money(msg.sender, "BirthFee-bid", autoBirthFee, autoBirthFee, _sireId, block.number); } // Transfers the balance of the sale auction contract to the Core contract function withdrawAuctionBalances() external onlyAdministrator { saleAuction.withdrawBalance(); breedingAuction.withdrawBalance(); } function sendGift(uint256 _flowerId, address _to) external payable whenNotStopped { require(isOwnerOf(msg.sender, _flowerId)); require(isReadyToAction(_flowerId)); transferFrom(msg.sender, _to, _flowerId); } function makeGift(uint256 _flowerId) external payable whenNotStopped { require(isOwnerOf(msg.sender, _flowerId)); require(isReadyToAction(_flowerId)); require(msg.value >= giftFee); transferFrom(msg.sender, giftHolderAddress, _flowerId); giftHolderAddress.transfer(msg.value); emit Money(msg.sender, "MakeGift", msg.value, msg.value, _flowerId, block.number); } } contract FlowerMinting is FlowerAuction { // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of cats the contract owner has created uint256 public promoCreatedCount; uint256 public gen0CreatedCount; // Create promo flower function createPromoFlower(uint256 _genes, address _owner) external onlyAdministrator { address flowerOwner = _owner; if (flowerOwner == address(0)) { flowerOwner = adminAddress; } promoCreatedCount++; gen0CreatedCount++; _createFlower(0, 0, 0, _genes, flowerOwner); } function createGen0Auction(uint256 _genes, uint64 _auctionStartAt) external onlyAdministrator { uint256 flowerId = _createFlower(0, 0, 0, _genes, address(gen0SellerAddress)); tokenApprovals[flowerId] = saleAuction; //approve(saleAuction, flowerId); gen0CreatedCount++; saleAuction.createAuction(flowerId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(gen0SellerAddress), _auctionStartAt); } // Computes the next gen0 auction starting price, given the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } function setGen0SellerAddress(address _newAddress) external onlyAdministrator { gen0SellerAddress = _newAddress; saleAuction.setGen0SellerAddress(_newAddress); } function setGiftHolderAddress(address _newAddress) external onlyAdministrator { giftHolderAddress = _newAddress; } } contract FlowerCore is FlowerMinting { constructor() public { stopped = true; rootAddress = msg.sender; adminAddress = msg.sender; _createFlower(0, 0, 0, uint256(-1), address(0)); } // Get flower information function getFlower(uint256 _id) external view returns (bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes) { Flower storage flower = flowers[_id]; isReady = (flower.cooldownEndBlock <= block.number); cooldownIndex = uint256(flower.cooldownIndex); nextActionAt = uint256(flower.cooldownEndBlock); birthTime = uint256(flower.birthTime); matronId = uint256(flower.matronId); sireId = uint256(flower.sireId); generation = uint256(flower.generation); genes = flower.genes; } // Start the game function unstop() public onlyAdministrator whenStopped { require(geneScience != address(0)); super.setStart(); } function withdrawBalance() external onlyAdministrator { rootAddress.transfer(address(this).balance); } }
TOD1
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval(address indexed owner,address indexed spender,uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // ERC20 standard token contract NBEToken is StandardToken { address public admin; string public name = "NBEToken"; string public symbol = "NBE"; uint8 public decimals = 18; uint256 public INITIAL_SUPPLY = 10000000000000000000000000000; mapping (address => uint256) public frozenTimestamp; bool public exchangeFlag = true; uint256 public minWei = 1; // 1 wei 1eth = 1*10^18 wei uint256 public maxWei = 20000000000000000000000; // 20000 eth uint256 public maxRaiseAmount = 500000000000000000000000; // 500000 eth uint256 public raisedAmount = 0; // 0 eth uint256 public raiseRatio = 10000; // 1eth = 10000 constructor() public { totalSupply_ = INITIAL_SUPPLY; admin = msg.sender; balances[msg.sender] = INITIAL_SUPPLY; } function() public payable { require(msg.value > 0); if (exchangeFlag) { if (msg.value >= minWei && msg.value <= maxWei){ if (raisedAmount < maxRaiseAmount) { uint256 valueNeed = msg.value; raisedAmount = raisedAmount.add(msg.value); if (raisedAmount > maxRaiseAmount) { uint256 valueLeft = raisedAmount.sub(maxRaiseAmount); valueNeed = msg.value.sub(valueLeft); msg.sender.transfer(valueLeft); raisedAmount = maxRaiseAmount; } if (raisedAmount >= maxRaiseAmount) { exchangeFlag = false; } uint256 _value = valueNeed.mul(raiseRatio); require(_value <= balances[admin]); balances[admin] = balances[admin].sub(_value); balances[msg.sender] = balances[msg.sender].add(_value); emit Transfer(admin, msg.sender, _value); } } else { msg.sender.transfer(msg.value); } } else { msg.sender.transfer(msg.value); } } /** * admin */ function changeAdmin( address _newAdmin ) public returns (bool) { require(msg.sender == admin); require(_newAdmin != address(0)); balances[_newAdmin] = balances[_newAdmin].add(balances[admin]); balances[admin] = 0; admin = _newAdmin; return true; } // withdraw admin function withdraw ( uint256 _amount ) public returns (bool) { require(msg.sender == admin); msg.sender.transfer(_amount); return true; } /** * */ function transfer( address _to, uint256 _value ) public returns (bool) { // require(!frozenAccount[msg.sender]); require(now > frozenTimestamp[msg.sender]); require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } //******************************************************************************** // function getFrozenTimestamp( address _target ) public view returns (uint256) { require(_target != address(0)); return frozenTimestamp[_target]; } // function getBalance() public view returns (uint256) { return address(this).balance; } // change flag function setExchangeFlag ( bool _flag ) public returns (bool) { require(msg.sender == admin); exchangeFlag = _flag; return true; } // change ratio function setRaiseRatio ( uint256 _value ) public returns (bool) { require(msg.sender == admin); raiseRatio = _value; return true; } }
TOD1
pragma solidity ^0.4.11; contract SafeMath { /* standard uint256 functions */ function add(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x + y) >= x); } function sub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x - y) <= x); } function mul(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x * y) >= x); } function div(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x / y; } function min(uint256 x, uint256 y) constant internal returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) constant internal returns (uint256 z) { return x >= y ? x : y; } /* uint128 functions (h is for half) */ function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x + y) >= x); } function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x - y) <= x); } function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x * y) >= x); } function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = x / y; } function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) { return x <= y ? x : y; } function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) { return x >= y ? x : y; } /* int256 functions */ function imin(int256 x, int256 y) constant internal returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) constant internal returns (int256 z) { return x >= y ? x : y; } /* WAD math */ uint128 constant WAD = 10 ** 18; function wadd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function wsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + WAD / 2) / WAD); } function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * WAD + y / 2) / y); } function wmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function wmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } /* RAY math */ uint128 constant RAY = 10 ** 27; function radd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function rsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + RAY / 2) / RAY); } function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * RAY + y / 2) / y); } function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) { // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } function rmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function rmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } function cast(uint256 x) constant internal returns (uint128 z) { assert((z = uint128(x)) == x); } } /// @dev `Owned` is a base level contract that assigns an `owner` that can be /// later changed contract Owned { /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require(msg.sender == owner) ; _; } address public owner; /// @notice The Constructor assigns the message sender to be `owner` function Owned() { owner = msg.sender; } address public newOwner; /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner. 0x0 can be used to create /// an unowned neutral vault, however that cannot be undone function changeOwner(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } } contract Contribution is SafeMath, Owned { uint256 public constant MIN_FUND = (0.01 ether); uint256 public constant CRAWDSALE_START_DAY = 1; uint256 public constant CRAWDSALE_END_DAY = 7; uint256 public dayCycle = 24 hours; uint256 public fundingStartTime = 0; address public ethFundDeposit = 0; address public investorDeposit = 0; bool public isFinalize = false; bool public isPause = false; mapping (uint => uint) public dailyTotals; //total eth per day mapping (uint => mapping (address => uint)) public userBuys; // otal eth per day per user uint256 public totalContributedETH = 0; //total eth of 7 days // events event LogBuy (uint window, address user, uint amount); event LogCreate (address ethFundDeposit, address investorDeposit, uint fundingStartTime, uint dayCycle); event LogFinalize (uint finalizeTime); event LogPause (uint finalizeTime, bool pause); function Contribution (address _ethFundDeposit, address _investorDeposit, uint256 _fundingStartTime, uint256 _dayCycle) { require( now < _fundingStartTime ); require( _ethFundDeposit != address(0) ); fundingStartTime = _fundingStartTime; dayCycle = _dayCycle; ethFundDeposit = _ethFundDeposit; investorDeposit = _investorDeposit; LogCreate(_ethFundDeposit, _investorDeposit, _fundingStartTime,_dayCycle); } //crawdsale entry function () payable { require(!isPause); require(!isFinalize); require( msg.value >= MIN_FUND ); //eth >= 0.01 at least ethFundDeposit.transfer(msg.value); buy(today(), msg.sender, msg.value); } function importExchangeSale(uint256 day, address _exchangeAddr, uint _amount) onlyOwner { buy(day, _exchangeAddr, _amount); } function buy(uint256 day, address _addr, uint256 _amount) internal { require( day >= CRAWDSALE_START_DAY && day <= CRAWDSALE_END_DAY ); //record user's buy amount userBuys[day][_addr] += _amount; dailyTotals[day] += _amount; totalContributedETH += _amount; LogBuy(day, _addr, _amount); } function kill() onlyOwner { selfdestruct(owner); } function pause(bool _isPause) onlyOwner { isPause = _isPause; LogPause(now,_isPause); } function finalize() onlyOwner { isFinalize = true; LogFinalize(now); } function today() constant returns (uint) { return sub(now, fundingStartTime) / dayCycle + 1; } }
TOD1
pragma solidity ^0.4.23; contract Owned { address public owner; address public newOwner; constructor() public { owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } event OwnerUpdate(address _prevOwner, address _newOwner); } contract ReentrancyHandlingContract{ bool locked; modifier noReentrancy() { require(!locked); locked = true; _; locked = false; } } contract ERC20TokenInterface { function totalSupply() public constant returns (uint256 _totalSupply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Crowdsale is ReentrancyHandlingContract, Owned { enum state { pendingStart, crowdsale, crowdsaleEnded } struct ContributorData { uint contributionAmount; uint tokensIssued; } struct Tier { uint minContribution; uint maxContribution; uint bonus; bool tierActive; } mapping (address => uint) public verifiedAddresses; mapping(uint => Tier) public tierList; uint public nextFreeTier = 1; state public crowdsaleState = state.pendingStart; address public multisigAddress; uint public crowdsaleStartBlock; uint public crowdsaleEndedBlock; mapping(address => ContributorData) public contributorList; uint public nextContributorIndex; mapping(uint => address) public contributorIndexes; uint public minCap; uint public maxCap; uint public ethRaised; uint public tokensIssued = 0; uint public blocksInADay; uint public ethToTokenConversion; event CrowdsaleStarted(uint blockNumber); event CrowdsaleEnded(uint blockNumber); event ErrorSendingETH(address to, uint amount); event MinCapReached(uint blockNumber); event MaxCapReached(uint blockNumber); function() noReentrancy payable public { require(crowdsaleState != state.crowdsaleEnded); require(isAddressVerified(msg.sender)); bool stateChanged = checkCrowdsaleState(); if (crowdsaleState == state.crowdsale) { processTransaction(msg.sender, msg.value); } else { refundTransaction(stateChanged); } } function checkCrowdsaleState() internal returns (bool) { if (tokensIssued == maxCap && crowdsaleState != state.crowdsaleEnded) { crowdsaleState = state.crowdsaleEnded; emit CrowdsaleEnded(block.number); return true; } if (block.number >= crowdsaleStartBlock && block.number <= crowdsaleEndedBlock) { if (crowdsaleState != state.crowdsale) { crowdsaleState = state.crowdsale; emit CrowdsaleStarted(block.number); return true; } } else { if (crowdsaleState != state.crowdsaleEnded && block.number > crowdsaleEndedBlock) { crowdsaleState = state.crowdsaleEnded; emit CrowdsaleEnded(block.number); return true; } } return false; } function refundTransaction(bool _stateChanged) internal { if (_stateChanged) { msg.sender.transfer(msg.value); } else { revert(); } } function setEthToTokenConversion(uint _ratio) onlyOwner public { require(crowdsaleState == state.pendingStart); ethToTokenConversion = _ratio; } function setMaxCap(uint _maxCap) onlyOwner public { require(crowdsaleState == state.pendingStart); maxCap = _maxCap; } function calculateEthToToken(uint _eth, uint _bonus) constant public returns(uint) { uint bonusTokens; if (_bonus != 0) { bonusTokens = ((_eth * ethToTokenConversion) * _bonus) / 100; } return (_eth * ethToTokenConversion) + bonusTokens; } function calculateTokenToEth(uint _token, uint _bonus) constant public returns(uint) { uint ethTokenWithBonus = ethToTokenConversion; if (_bonus != 0){ ethTokenWithBonus = ((ethToTokenConversion * _bonus) / 100) + ethToTokenConversion; } return _token / ethTokenWithBonus; } function processTransaction(address _contributor, uint _amount) internal { uint contributionAmount = 0; uint returnAmount = 0; uint tokensToGive = 0; uint contributorTier; uint minContribution; uint maxContribution; uint bonus; (contributorTier, minContribution, maxContribution, bonus) = getContributorData(_contributor); if (block.number >= crowdsaleStartBlock && block.number < crowdsaleStartBlock + blocksInADay){ require(_amount >= minContribution); require(contributorTier == 1 || contributorTier == 2 || contributorTier == 5 || contributorTier == 6 || contributorTier == 7 || contributorTier == 8); if (_amount > maxContribution && maxContribution != 0){ contributionAmount = maxContribution; returnAmount = _amount - maxContribution; } else { contributionAmount = _amount; } tokensToGive = calculateEthToToken(contributionAmount, bonus); } else if (block.number >= crowdsaleStartBlock + blocksInADay && block.number < crowdsaleStartBlock + 2 * blocksInADay) { require(_amount >= minContribution); require(contributorTier == 3 || contributorTier == 5 || contributorTier == 6 || contributorTier == 7 || contributorTier == 8); if (_amount > maxContribution && maxContribution != 0) { contributionAmount = maxContribution; returnAmount = _amount - maxContribution; } else { contributionAmount = _amount; } tokensToGive = calculateEthToToken(contributionAmount, bonus); } else { require(_amount >= minContribution); if (_amount > maxContribution && maxContribution != 0) { contributionAmount = maxContribution; returnAmount = _amount - maxContribution; } else { contributionAmount = _amount; } if(contributorTier == 5 || contributorTier == 6 || contributorTier == 7 || contributorTier == 8){ tokensToGive = calculateEthToToken(contributionAmount, bonus); }else{ tokensToGive = calculateEthToToken(contributionAmount, 0); } } if (tokensToGive > (maxCap - tokensIssued)) { if (block.number >= crowdsaleStartBlock && block.number < crowdsaleStartBlock + blocksInADay){ contributionAmount = calculateTokenToEth(maxCap - tokensIssued, bonus); }else if (block.number >= crowdsaleStartBlock + blocksInADay && block.number < crowdsaleStartBlock + 2 * blocksInADay) { contributionAmount = calculateTokenToEth(maxCap - tokensIssued, bonus); }else{ if(contributorTier == 5 || contributorTier == 6 || contributorTier == 7 || contributorTier == 8){ contributionAmount = calculateTokenToEth(maxCap - tokensIssued, bonus); }else{ contributionAmount = calculateTokenToEth(maxCap - tokensIssued, 0); } } returnAmount = _amount - contributionAmount; tokensToGive = maxCap - tokensIssued; emit MaxCapReached(block.number); } if (contributorList[_contributor].contributionAmount == 0) { contributorIndexes[nextContributorIndex] = _contributor; nextContributorIndex += 1; } contributorList[_contributor].contributionAmount += contributionAmount; ethRaised += contributionAmount; if (tokensToGive > 0) { contributorList[_contributor].tokensIssued += tokensToGive; tokensIssued += tokensToGive; } if (returnAmount != 0) { _contributor.transfer(returnAmount); } } function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public { ERC20TokenInterface(_tokenAddress).transfer(_to, _amount); } function withdrawEth() onlyOwner public { require(address(this).balance != 0); require(tokensIssued >= minCap); multisigAddress.transfer(address(this).balance); } function investorCount() constant public returns(uint) { return nextContributorIndex; } function setCrowdsaleStartBlock(uint _block) onlyOwner public { require(crowdsaleState == state.pendingStart); crowdsaleStartBlock = _block; } function setCrowdsaleEndBlock(uint _block) onlyOwner public { require(crowdsaleState == state.pendingStart); crowdsaleEndedBlock = _block; } function isAddressVerified(address _address) public view returns (bool) { if (verifiedAddresses[_address] == 0){ return false; } else { return true; } } function getContributorData(address _contributor) public view returns (uint, uint, uint, uint) { uint contributorTier = verifiedAddresses[_contributor]; return (contributorTier, tierList[contributorTier].minContribution, tierList[contributorTier].maxContribution, tierList[contributorTier].bonus); } function addAddress(address _newAddress, uint _tier) public onlyOwner { require(verifiedAddresses[_newAddress] == 0); verifiedAddresses[_newAddress] = _tier; } function removeAddress(address _oldAddress) public onlyOwner { require(verifiedAddresses[_oldAddress] != 0); verifiedAddresses[_oldAddress] = 0; } function batchAddAddresses(address[] _addresses, uint[] _tiers) public onlyOwner { require(_addresses.length == _tiers.length); for (uint cnt = 0; cnt < _addresses.length; cnt++) { assert(verifiedAddresses[_addresses[cnt]] != 0); verifiedAddresses[_addresses[cnt]] = _tiers[cnt]; } } } contract MoneyRebelCrowdsaleContract is Crowdsale { constructor() public { crowdsaleStartBlock = 5578000; crowdsaleEndedBlock = 5618330; minCap = 0 * 10**18; maxCap = 744428391 * 10**18; ethToTokenConversion = 13888; blocksInADay = 5760; multisigAddress = 0x352C30f3092556CD42fE39cbCF585f33CE1C20bc; tierList[1] = Tier(2*10**17,35*10**18,10, true); tierList[2] = Tier(2*10**17,35*10**18,10, true); tierList[3] = Tier(2*10**17,25*10**18,0, true); tierList[4] = Tier(2*10**17,100000*10**18,0, true); tierList[5] = Tier(2*10**17,100000*10**18,8, true); tierList[6] = Tier(2*10**17,100000*10**18,10, true); tierList[7] = Tier(2*10**17,100000*10**18,12, true); tierList[8] = Tier(2*10**17,100000*10**18,15, true); } }
TOD1
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract TN is Ownable, MintableToken { using SafeMath for uint256; string public constant name = "TNcoin"; string public constant symbol = "TNC"; uint32 public constant decimals = 18; address public addressTeam; uint public summTeam; function TN() public { addressTeam = 0x799AAE2118f10d5148C9D7275EaF95bc0Cb6D6f9; summTeam = 5050000 * (10 ** uint256(decimals)); // Founders and supporters initial Allocations mint(addressTeam, summTeam); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where Contributors can make * token Contributions and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. The contract requires a MintableToken that will be * minted as contributions arrive, note that the crowdsale contract * must be owner of the token in order to be able to mint it. */ contract Crowdsale is Ownable { using SafeMath for uint256; // soft cap uint softcap; // hard cap uint hardcap; TN public token; // balances for softcap mapping(address => uint) public balances; // start and end timestamps where investments are allowed (both inclusive) //ico //start uint256 public startIco; //end uint256 public endIco; //token distribution // uint256 public maxIco; uint256 public totalSoldTokens; // how many token units a Contributor gets per wei uint256 public rateIco; // address where funds are collected address public wallet; /** * event for token Procurement logging * @param contributor who Pledged for the tokens * @param beneficiary who got the tokens * @param value weis Contributed for Procurement * @param amount amount of tokens Procured */ event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale() public { token = createTokenContract(); //soft cap in tokens softcap = 10000000 * 1 ether; hardcap = 50000000 * 1 ether; // start and end timestamps where investments are allowed //ico //start startIco = 1526403600;//2018 May 15, 12pm CST //end endIco = 1539622800;//2018 Oct 15 at 12pm CST // rate; rateIco = 670; // address where funds are collected wallet = 0xaa6072Cb5EcB3A1567F8Fdb4601620C4a808fD6c; } function setRateIco(uint _rateIco) public onlyOwner { rateIco = _rateIco; } // fallback function can be used to Procure tokens function () external payable { procureTokens(msg.sender); } function createTokenContract() internal returns (TN) { return new TN(); } // low level token Pledge function function procureTokens(address beneficiary) public payable { uint256 tokens; uint256 weiAmount = msg.value; uint256 backAmount; require(beneficiary != address(0)); //ico if (now >= startIco && now < endIco && totalSoldTokens < hardcap){ tokens = weiAmount.mul(rateIco); if (hardcap.sub(totalSoldTokens) < tokens){ tokens = hardcap.sub(totalSoldTokens); weiAmount = tokens.div(rateIco); backAmount = msg.value.sub(weiAmount); } totalSoldTokens = totalSoldTokens.add(tokens); } require(tokens > 0); balances[msg.sender] = balances[msg.sender].add(msg.value); token.mint(msg.sender, tokens); if (backAmount > 0){ balances[msg.sender] = balances[msg.sender].sub(backAmount); msg.sender.transfer(backAmount); } emit TokenProcurement(msg.sender, beneficiary, weiAmount, tokens); } function refund() public{ require(totalSoldTokens < softcap && now > endIco); require(balances[msg.sender] > 0); uint value = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(value); } function transferEthToMultisig() public onlyOwner { address _this = this; require(totalSoldTokens >= softcap && now > endIco); wallet.transfer(_this.balance); } }
TOD1
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation */ contract MintableToken is StandardToken, Ownable { uint256 public hardCap; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title CABoxToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract CABoxToken is MintableToken, Destructible { string public constant name = "CABox"; string public constant symbol = "CAB"; uint8 public constant decimals = 18; /** * @dev Constructor that gives msg.sender all of existing tokens. */ function CABoxToken() public { hardCap = 500 * 1000000 * (10 ** uint256(decimals)); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply.add(_amount) <= hardCap); return super.mint(_to, _amount); } } /** * @title CABoxCrowdsale * @dev CABoxCrowdsale is a completed contract for managing a token crowdsale. * CABoxCrowdsale have a start and end timestamps, where investors can make * token purchases and the CABoxCrowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract CABoxCrowdsale is Ownable{ using SafeMath for uint256; // The token being sold CABoxToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // address where development funds are collected address public devWallet; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event TokenContractUpdated(bool state); event WalletAddressUpdated(bool state); function CABoxCrowdsale() public { token = createTokenContract(); startTime = 1535155200; endTime = 1540771200; wallet = 0x9BeAbD0aeB08d18612d41210aFEafD08fb84E9E8; devWallet = 0x13dF1d8F51324a237552E87cebC3f501baE2e972; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (CABoxToken) { return new CABoxToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 bonusRate = getBonusRate(); uint256 tokens = weiAmount.mul(bonusRate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function getBonusRate() internal view returns (uint256) { uint64[5] memory tokenRates = [uint64(24000),uint64(20000),uint64(16000),uint64(12000),uint64(8000)]; // apply bonus for time uint64[5] memory timeStartsBoundaries = [uint64(1535155200),uint64(1538352000),uint64(1538956800),uint64(1539561600),uint64(1540166400)]; uint64[5] memory timeEndsBoundaries = [uint64(1538352000),uint64(1538956800),uint64(1539561600),uint64(1540166400),uint64(1540771200)]; uint[5] memory timeRates = [uint(500),uint(250),uint(200),uint(150),uint(100)]; uint256 bonusRate = tokenRates[0]; for (uint i = 0; i < 5; i++) { bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]); if (timeInBound) { bonusRate = tokenRates[i] + tokenRates[i] * timeRates[i] / 1000; } } return bonusRate; } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value * 750 / 1000); devWallet.transfer(msg.value * 250 / 1000); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool nonZeroPurchase = msg.value != 0; bool withinPeriod = now >= startTime && now <= endTime; return nonZeroPurchase && withinPeriod; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool timeEnded = now > endTime; return timeEnded; } // update token contract function updateCABoxToken(address _tokenAddress) onlyOwner{ require(_tokenAddress != address(0)); token.transferOwnership(_tokenAddress); TokenContractUpdated(true); } }
TOD1
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // // Funds Gateway contract // // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferProposed(address indexed _from, address indexed _to); event OwnershipTransferConfirmed(address indexed _from, address indexed _to); modifier onlyOwner { require(msg.sender == owner); _; } constructor() public{ owner = msg.sender; } function transferOwnership(address _newOwner) onlyOwner public{ require(_newOwner != owner); emit OwnershipTransferProposed(owner, _newOwner); newOwner = _newOwner; } function confirmOwnership() public{ assert(msg.sender == newOwner); emit OwnershipTransferConfirmed(owner, newOwner); owner = newOwner; } } //from ERC20 standard contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract Gateway is Owned { address public targetWallet; address public whitelistWallet; bool public gatewayOpened = false; mapping(address => bool) public whitelist; event TargetWalletUpdated(address _newWallet); event WhitelistWalletUpdated(address _newWhitelistWallet); event GatewayStatusUpdated(bool _status); event WhitelistUpdated(address indexed _participant, bool _status); event PassedGateway(address _participant, uint _value); constructor() public{ targetWallet = owner; whitelistWallet = owner; newOwner = address(0x0); } function () payable public{ passGateway(); } function addToWhitelist(address _participant) external{ require(msg.sender == whitelistWallet || msg.sender == owner); whitelist[_participant] = true; emit WhitelistUpdated(_participant, true); } function addToWhitelistMultiple(address[] _participants) external{ require(msg.sender == whitelistWallet || msg.sender == owner); for (uint i = 0; i < _participants.length; i++) { whitelist[_participants[i]] = true; emit WhitelistUpdated(_participants[i], true); } } function removeFromWhitelist(address _participant) external{ require(msg.sender == whitelistWallet || msg.sender == owner); whitelist[_participant] = false; emit WhitelistUpdated(_participant, false); } function removeFromWhitelistMultiple(address[] _participants) external{ require(msg.sender == whitelistWallet || msg.sender == owner); for (uint i = 0; i < _participants.length; i++) { whitelist[_participants[i]] = false; emit WhitelistUpdated(_participants[i], false); } } function setTargetWallet(address _wallet) onlyOwner external{ require(_wallet != address(0x0)); targetWallet = _wallet; emit TargetWalletUpdated(_wallet); } function setWhitelistWallet(address _wallet) onlyOwner external{ whitelistWallet = _wallet; emit WhitelistWalletUpdated(_wallet); } function openGateway() onlyOwner external{ require(!gatewayOpened); gatewayOpened = true; emit GatewayStatusUpdated(true); } function closeGateway() onlyOwner external{ require(gatewayOpened); gatewayOpened = false; emit GatewayStatusUpdated(false); } function passGateway() private{ require(gatewayOpened); require(whitelist[msg.sender]); // sends Eth forward; covers edge case of mining/selfdestructing Eth to the contract address // note: address uses a different "transfer" than ERC20. address(targetWallet).transfer(address(this).balance); // log event emit PassedGateway(msg.sender, msg.value); } //from ERC20 standard //Used if someone sends tokens to the bouncer contract. function transferAnyERC20Token( address tokenAddress, uint256 tokens ) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
TOD1
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(uint256 rate, address wallet, IERC20 token) internal { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param cap Max amount of wei to be contributed */ constructor(uint256 cap) internal { require(cap > 0); _cap = cap; } /** * @return the cap of the crowdsale. */ function cap() public view returns(uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen()); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor(uint256 openingTime, uint256 closingTime) internal { // solium-disable-next-line security/no-block-members require(openingTime >= block.timestamp); require(closingTime > openingTime); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns(uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns(uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale with a one-off finalization action, where one * can do extra work after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized; event CrowdsaleFinalized(); constructor() internal { _finalized = false; } /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!_finalized); require(hasClosed()); _finalized = true; _finalization(); emit CrowdsaleFinalized(); } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super._finalization() to ensure the chain of finalization is * executed entirely. */ function _finalization() internal { } } // File: openzeppelin-solidity/contracts/ownership/Secondary.sol /** * @title Secondary * @dev A Secondary contract can only be used by its primary account (the one that created it) */ contract Secondary { address private _primary; event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor() internal { _primary = msg.sender; emit PrimaryTransferred(_primary); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(msg.sender == _primary); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0)); _primary = recipient; emit PrimaryTransferred(_primary); } } // File: openzeppelin-solidity/contracts/payment/escrow/Escrow.sol /** * @title Escrow * @dev Base escrow contract, holds funds designated for a payee until they * withdraw them. * @dev Intended usage: This contract (and derived escrow contracts) should be a * standalone contract, that only interacts with the contract that instantiated * it. That way, it is guaranteed that all Ether will be handled according to * the Escrow rules, and there is no need to check for payable functions or * transfers in the inheritance tree. The contract that uses the escrow as its * payment method should be its primary, and provide public methods redirecting * to the escrow's deposit and withdraw. */ contract Escrow is Secondary { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public onlyPrimary payable { uint256 amount = msg.value; _deposits[payee] = _deposits[payee].add(amount); emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payee) public onlyPrimary { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.transfer(payment); emit Withdrawn(payee, payment); } } // File: openzeppelin-solidity/contracts/payment/escrow/ConditionalEscrow.sol /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. * @dev Intended usage: See Escrow.sol. Same usage guidelines apply here. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param payee The destination address of the funds. */ function withdrawalAllowed(address payee) public view returns (bool); function withdraw(address payee) public { require(withdrawalAllowed(payee)); super.withdraw(payee); } } // File: openzeppelin-solidity/contracts/payment/escrow/RefundEscrow.sol /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple * parties. * @dev Intended usage: See Escrow.sol. Same usage guidelines apply here. * @dev The primary account (that is, the contract that instantiates this * contract) may deposit, close the deposit period, and allow for either * withdrawal by the beneficiary, or refunds to the depositors. All interactions * with RefundEscrow will be made through the primary contract. See the * RefundableCrowdsale contract for an example of RefundEscrow’s use. */ contract RefundEscrow is ConditionalEscrow { enum State { Active, Refunding, Closed } event RefundsClosed(); event RefundsEnabled(); State private _state; address private _beneficiary; /** * @dev Constructor. * @param beneficiary The beneficiary of the deposits. */ constructor(address beneficiary) public { require(beneficiary != address(0)); _beneficiary = beneficiary; _state = State.Active; } /** * @return the current state of the escrow. */ function state() public view returns (State) { return _state; } /** * @return the beneficiary of the escrow. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @dev Stores funds that may later be refunded. * @param refundee The address funds will be sent to if a refund occurs. */ function deposit(address refundee) public payable { require(_state == State.Active); super.deposit(refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyPrimary { require(_state == State.Active); _state = State.Closed; emit RefundsClosed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyPrimary { require(_state == State.Active); _state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(_state == State.Closed); _beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address payee) public view returns (bool) { return _state == State.Refunding; } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * WARNING: note that if you allow tokens to be traded before the goal * is met, then an attack is possible in which the attacker purchases * tokens from the crowdsale and when they sees that the goal is * unlikely to be met, they sell their tokens (possibly at a discount). * The attacker will be refunded when the crowdsale is finalized, and * the users that purchased from them will be left with worthless * tokens. There are many possible ways to avoid this, like making the * the crowdsale inherit from PostDeliveryCrowdsale, or imposing * restrictions on token trading until the crowdsale is finalized. * This is being discussed in * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/877 * This contract will be updated when we agree on a general solution * for this problem. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 private _goal; // refund escrow used to hold funds while crowdsale is running RefundEscrow private _escrow; /** * @dev Constructor, creates RefundEscrow. * @param goal Funding goal */ constructor(uint256 goal) internal { require(goal > 0); _escrow = new RefundEscrow(wallet()); _goal = goal; } /** * @return minimum amount of funds to be raised in wei. */ function goal() public view returns(uint256) { return _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful * @param beneficiary Whose refund will be claimed. */ function claimRefund(address beneficiary) public { require(finalized()); require(!goalReached()); _escrow.withdraw(beneficiary); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised() >= _goal; } /** * @dev escrow finalization task, called when finalize() is called */ function _finalization() internal { if (goalReached()) { _escrow.close(); _escrow.beneficiaryWithdraw(); } else { _escrow.enableRefunds(); } super._finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { _escrow.deposit.value(msg.value)(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address to, uint256 value ) public onlyMinter returns (bool) { _mint(to, value); return true; } } // File: openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { constructor() internal {} /** * @dev Overrides delivery by minting tokens upon purchase. * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { // Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(token())).mint(beneficiary, tokenAmount)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; constructor(uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap for the token minting. */ function cap() public view returns(uint256) { return _cap; } function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap); super._mint(account, value); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private pausers; constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: contracts\Zion.sol contract Zion is ERC20Mintable, ERC20Detailed, Pausable { // define initial coin supply here uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals())); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("Zion", "ZION", 18) { _mint(msg.sender, INITIAL_SUPPLY); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from,address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } }
TOD1
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/math/SafeMath.sol */ 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); 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/ownership/Ownable.sol */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/lifecycle/Pausable.sol */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/token/ERC20Basic.sol */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/token/BasicToken.sol */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/token/ERC20.sol */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/token/StandardToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/token/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; address public mintAddress; modifier canMint() { require(!mintingFinished); _; } modifier onlyMint() { require(msg.sender == mintAddress); _; } /** * @dev Function to change address that is allowed to do emission. * @param _mintAddress Address of the emission contract. */ function setMintAddress(address _mintAddress) public onlyOwner { require(_mintAddress != address(0)); mintAddress = _mintAddress; } /** * @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 onlyMint canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyMint canMint returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time * @dev Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.4.0/contracts/token/TokenTimelock.sol */ contract TokenTimelock { // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; /** * @dev The TokenTimelock constructor sets token address, beneficiary and time to release. * @param _token Address of the token * @param _beneficiary Address that will receive the tokens after release * @param _releaseTime Time that will allow release the tokens */ function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @dev Transfers tokens held by timelock to beneficiary. */ function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.transfer(beneficiary, amount); } } /** * @title CraftyCrowdsale * @dev CraftyCrowdsale is a contract for managing a Crafty token crowdsale. */ contract CraftyCrowdsale is Pausable { using SafeMath for uint256; // Amount received from each address mapping(address => uint256) received; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public preSaleStart; uint256 public preSaleEnd; uint256 public saleStart; uint256 public saleEnd; // amount of tokens sold uint256 public issuedTokens = 0; // token cap uint256 public constant hardCap = 5000000000 * 10**8; // 50% // token wallets uint256 constant teamCap = 1450000000 * 10**8; // 14.5% uint256 constant advisorCap = 450000000 * 10**8; // 4.5% uint256 constant bountyCap = 100000000 * 10**8; // 1% uint256 constant fundCap = 3000000000 * 10**8; // 30% // Number of days the tokens will be locked uint256 constant lockTime = 180 days; // wallets address public etherWallet; address public teamWallet; address public advisorWallet; address public fundWallet; address public bountyWallet; // timelocked tokens TokenTimelock teamTokens; uint256 public rate; enum State { BEFORE_START, SALE, REFUND, CLOSED } State currentState = State.BEFORE_START; /** * @dev Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount); /** * @dev Event for refund * @param to who sent wei * @param amount amount of wei refunded */ event Refund(address indexed to, uint256 amount); /** * @dev modifier to allow token creation only when the sale is on */ modifier saleIsOn() { require( ( (now >= preSaleStart && now < preSaleEnd) || (now >= saleStart && now < saleEnd) ) && issuedTokens < hardCap && currentState == State.SALE ); _; } /** * @dev modifier to allow action only before sale */ modifier beforeSale() { require( now < preSaleStart); _; } /** * @dev modifier that fails if state doesn't match */ modifier inState(State _state) { require(currentState == _state); _; } /** * @dev CraftyCrowdsale constructor sets the token, period and exchange rate * @param _token The address of Crafty Token. * @param _preSaleStart The start time of pre-sale. * @param _preSaleEnd The end time of pre-sale. * @param _saleStart The start time of sale. * @param _saleEnd The end time of sale. * @param _rate The exchange rate of tokens. */ function CraftyCrowdsale(address _token, uint256 _preSaleStart, uint256 _preSaleEnd, uint256 _saleStart, uint256 _saleEnd, uint256 _rate) public { require(_token != address(0)); require(_preSaleStart < _preSaleEnd && _preSaleEnd < _saleStart && _saleStart < _saleEnd); require(_rate > 0); token = MintableToken(_token); preSaleStart = _preSaleStart; preSaleEnd = _preSaleEnd; saleStart = _saleStart; saleEnd = _saleEnd; rate = _rate; } /** * @dev Fallback function can be used to buy tokens */ function () public payable { if(msg.sender != owner) buyTokens(); } /** * @dev Function used to buy tokens */ function buyTokens() public saleIsOn whenNotPaused payable { require(msg.sender != address(0)); require(msg.value >= 20 finney); uint256 weiAmount = msg.value; uint256 currentRate = getRate(weiAmount); // calculate token amount to be created uint256 newTokens = weiAmount.mul(currentRate).div(10**18); require(issuedTokens.add(newTokens) <= hardCap); issuedTokens = issuedTokens.add(newTokens); received[msg.sender] = received[msg.sender].add(weiAmount); token.mint(msg.sender, newTokens); TokenPurchase(msg.sender, msg.sender, newTokens); etherWallet.transfer(msg.value); } /** * @dev Function used to change the exchange rate. * @param _rate The new rate. */ function setRate(uint256 _rate) public onlyOwner beforeSale { require(_rate > 0); rate = _rate; } /** * @dev Function used to set wallets and enable the sale. * @param _etherWallet Address of ether wallet. * @param _teamWallet Address of team wallet. * @param _advisorWallet Address of advisors wallet. * @param _bountyWallet Address of bounty wallet. * @param _fundWallet Address of fund wallet. */ function setWallets(address _etherWallet, address _teamWallet, address _advisorWallet, address _bountyWallet, address _fundWallet) public onlyOwner inState(State.BEFORE_START) { require(_etherWallet != address(0)); require(_teamWallet != address(0)); require(_advisorWallet != address(0)); require(_bountyWallet != address(0)); require(_fundWallet != address(0)); etherWallet = _etherWallet; teamWallet = _teamWallet; advisorWallet = _advisorWallet; bountyWallet = _bountyWallet; fundWallet = _fundWallet; uint256 releaseTime = saleEnd + lockTime; // Mint locked tokens teamTokens = new TokenTimelock(token, teamWallet, releaseTime); token.mint(teamTokens, teamCap); // Mint released tokens token.mint(advisorWallet, advisorCap); token.mint(bountyWallet, bountyCap); token.mint(fundWallet, fundCap); currentState = State.SALE; } /** * @dev Generate tokens to specific address, necessary to accept other cryptos. * @param beneficiary Address of the beneficiary. * @param newTokens Amount of tokens to be minted. */ function generateTokens(address beneficiary, uint256 newTokens) public onlyOwner { require(beneficiary != address(0)); require(newTokens > 0); require(issuedTokens.add(newTokens) <= hardCap); issuedTokens = issuedTokens.add(newTokens); token.mint(beneficiary, newTokens); TokenPurchase(msg.sender, beneficiary, newTokens); } /** * @dev Finish crowdsale and token minting. */ function finishCrowdsale() public onlyOwner inState(State.SALE) { require(now > saleEnd); // tokens not sold to fund uint256 unspentTokens = hardCap.sub(issuedTokens); token.mint(fundWallet, unspentTokens); currentState = State.CLOSED; token.finishMinting(); } /** * @dev Enable refund after sale. */ function enableRefund() public onlyOwner inState(State.CLOSED) { currentState = State.REFUND; } /** * @dev Check the amount of wei received by beneficiary. * @param beneficiary Address of beneficiary. */ function receivedFrom(address beneficiary) public view returns (uint256) { return received[beneficiary]; } /** * @dev Function used to claim wei if refund is enabled. */ function claimRefund() public whenNotPaused inState(State.REFUND) { require(received[msg.sender] > 0); uint256 amount = received[msg.sender]; received[msg.sender] = 0; msg.sender.transfer(amount); Refund(msg.sender, amount); } /** * @dev Function used to release token of team wallet. */ function releaseTeamTokens() public { teamTokens.release(); } /** * @dev Function used to reclaim ether by owner. */ function reclaimEther() public onlyOwner { owner.transfer(this.balance); } /** * @dev Get exchange rate based on time and amount. * @param amount Amount received. * @return An uint256 representing the exchange rate. */ function getRate(uint256 amount) internal view returns (uint256) { if(now < preSaleEnd) { require(amount >= 6797 finney); if(amount <= 8156 finney) return rate.mul(105).div(100); if(amount <= 9515 finney) return rate.mul(1055).div(1000); if(amount <= 10874 finney) return rate.mul(1065).div(1000); if(amount <= 12234 finney) return rate.mul(108).div(100); if(amount <= 13593 finney) return rate.mul(110).div(100); if(amount <= 27185 finney) return rate.mul(113).div(100); if(amount > 27185 finney) return rate.mul(120).div(100); } return rate; } }
TOD1
pragma solidity ^0.4.20; contract QUIZ_FF { function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.15; contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract Bounty0xPresale is Owned { // ------------------------------------------------------------------------------------- // TODO Before deployment of contract to Mainnet // 1. Confirm MINIMUM_PARTICIPATION_AMOUNT and MAXIMUM_PARTICIPATION_AMOUNT below // 2. Adjust PRESALE_MINIMUM_FUNDING and PRESALE_MAXIMUM_FUNDING to desired EUR // equivalents // 3. Adjust PRESALE_START_DATE and confirm the presale period // 4. Update TOTAL_PREALLOCATION to the total preallocations received // 5. Add each preallocation address and funding amount from the Sikoba bookmaker // to the constructor function // 6. Test the deployment to a dev blockchain or Testnet to confirm the constructor // will not run out of gas as this will vary with the number of preallocation // account entries // 7. A stable version of Solidity has been used. Check for any major bugs in the // Solidity release announcements after this version. // 8. Remember to send the preallocated funds when deploying the contract! // ------------------------------------------------------------------------------------- // contract closed bool private saleHasEnded = false; // set whitelisting filter on/off bool private isWhitelistingActive = true; // Keep track of the total funding amount uint256 public totalFunding; // Minimum and maximum amounts per transaction for public participants uint256 public constant MINIMUM_PARTICIPATION_AMOUNT = 0.1 ether; uint256 public MAXIMUM_PARTICIPATION_AMOUNT = 3.53 ether; // Minimum and maximum goals of the presale uint256 public constant PRESALE_MINIMUM_FUNDING = 1 ether; uint256 public constant PRESALE_MAXIMUM_FUNDING = 705 ether; // Total preallocation in wei //uint256 public constant TOTAL_PREALLOCATION = 15 ether; // Public presale period // Starts Nov 20 2017 @ 14:00PM (UTC) 2017-11-20T14:00:00+00:00 in ISO 8601 // Ends 1 weeks after the start uint256 public constant PRESALE_START_DATE = 1511186400; uint256 public constant PRESALE_END_DATE = PRESALE_START_DATE + 2 weeks; // Owner can clawback after a date in the future, so no ethers remain // trapped in the contract. This will only be relevant if the // minimum funding level is not reached // Dec 13 @ 13:00pm (UTC) 2017-12-03T13:00:00+00:00 in ISO 8601 uint256 public constant OWNER_CLAWBACK_DATE = 1512306000; /// @notice Keep track of all participants contributions, including both the /// preallocation and public phases /// @dev Name complies with ERC20 token standard, etherscan for example will recognize /// this and show the balances of the address mapping (address => uint256) public balanceOf; /// List of whitelisted participants mapping (address => bool) public earlyParticipantWhitelist; /// @notice Log an event for each funding contributed during the public phase /// @notice Events are not logged when the constructor is being executed during /// deployment, so the preallocations will not be logged event LogParticipation(address indexed sender, uint256 value, uint256 timestamp); function Bounty0xPresale () payable { //assertEquals(TOTAL_PREALLOCATION, msg.value); // Pre-allocations //addBalance(0xdeadbeef, 10 ether); //addBalance(0xcafebabe, 5 ether); //assertEquals(TOTAL_PREALLOCATION, totalFunding); } /// @notice A participant sends a contribution to the contract's address /// between the PRESALE_STATE_DATE and the PRESALE_END_DATE /// @notice Only contributions between the MINIMUM_PARTICIPATION_AMOUNT and /// MAXIMUM_PARTICIPATION_AMOUNT are accepted. Otherwise the transaction /// is rejected and contributed amount is returned to the participant's /// account /// @notice A participant's contribution will be rejected if the presale /// has been funded to the maximum amount function () payable { require(!saleHasEnded); // A participant cannot send funds before the presale start date require(now > PRESALE_START_DATE); // A participant cannot send funds after the presale end date require(now < PRESALE_END_DATE); // A participant cannot send less than the minimum amount require(msg.value >= MINIMUM_PARTICIPATION_AMOUNT); // A participant cannot send more than the maximum amount require(msg.value <= MAXIMUM_PARTICIPATION_AMOUNT); // If whitelist filtering is active, if so then check the contributor is in list of addresses if (isWhitelistingActive) { require(earlyParticipantWhitelist[msg.sender]); } // A participant cannot send funds if the presale has been reached the maximum funding amount require(safeIncrement(totalFunding, msg.value) <= PRESALE_MAXIMUM_FUNDING); // Register the participant's contribution addBalance(msg.sender, msg.value); } /// @notice The owner can withdraw ethers after the presale has completed, /// only if the minimum funding level has been reached function ownerWithdraw(uint256 value) external onlyOwner { if (totalFunding >= PRESALE_MAXIMUM_FUNDING) { owner.transfer(value); saleHasEnded = true; } else { // The owner cannot withdraw before the presale ends require(now >= PRESALE_END_DATE); // The owner cannot withdraw if the presale did not reach the minimum funding amount require(totalFunding >= PRESALE_MINIMUM_FUNDING); // Withdraw the amount requested owner.transfer(value); } } /// @notice The participant will need to withdraw their funds from this contract if /// the presale has not achieved the minimum funding level function participantWithdrawIfMinimumFundingNotReached(uint256 value) external { // Participant cannot withdraw before the presale ends require(now >= PRESALE_END_DATE); // Participant cannot withdraw if the minimum funding amount has been reached require(totalFunding <= PRESALE_MINIMUM_FUNDING); // Participant can only withdraw an amount up to their contributed balance assert(balanceOf[msg.sender] < value); // Participant's balance is reduced by the claimed amount. balanceOf[msg.sender] = safeDecrement(balanceOf[msg.sender], value); // Send ethers back to the participant's account msg.sender.transfer(value); } /// @notice The owner can clawback any ethers after a date in the future, so no /// ethers remain trapped in this contract. This will only be relevant /// if the minimum funding level is not reached function ownerClawback() external onlyOwner { // The owner cannot withdraw before the clawback date require(now >= OWNER_CLAWBACK_DATE); // Send remaining funds back to the owner owner.transfer(this.balance); } // Set addresses in whitelist function setEarlyParicipantWhitelist(address addr, bool status) external onlyOwner { earlyParticipantWhitelist[addr] = status; } /// Ability to turn of whitelist filtering after 24 hours function whitelistFilteringSwitch() external onlyOwner { if (isWhitelistingActive) { isWhitelistingActive = false; MAXIMUM_PARTICIPATION_AMOUNT = 30000 ether; } else { revert(); } } /// @dev Keep track of participants contributions and the total funding amount function addBalance(address participant, uint256 value) private { // Participant's balance is increased by the sent amount balanceOf[participant] = safeIncrement(balanceOf[participant], value); // Keep track of the total funding amount totalFunding = safeIncrement(totalFunding, value); // Log an event of the participant's contribution LogParticipation(participant, value, now); } /// @dev Throw an exception if the amounts are not equal function assertEquals(uint256 expectedValue, uint256 actualValue) private constant { assert(expectedValue == actualValue); } /// @dev Add a number to a base value. Detect overflows by checking the result is larger /// than the original base value. function safeIncrement(uint256 base, uint256 increment) private constant returns (uint256) { assert(increment >= base); return base + increment; } /// @dev Subtract a number from a base value. Detect underflows by checking that the result /// is smaller than the original base value function safeDecrement(uint256 base, uint256 decrement) private constant returns (uint256) { assert(decrement <= base); return base - decrement; } }
TOD1
pragma solidity ^0.4.23; contract Ownable { address owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } contract Mortal is Ownable { function kill() public onlyOwner { selfdestruct(owner); } } contract FireBet is Mortal{ uint minBet = 1000000; uint houseEdge = 1; //in % event Won(bool _status, uint _amount); constructor() payable public {} function() public { //fallback revert(); } function bet(uint _number) payable public { require(_number > 0 && _number <= 10); require(msg.value >= minBet); uint256 winningNumber = block.number % 10 + 1; if (_number == winningNumber) { uint amountWon = msg.value * (100 - houseEdge)/10; if(!msg.sender.send(amountWon)) revert(); emit Won(true, amountWon); } else { emit Won(false, 0); } } function checkContractBalance() public view returns(uint) { return address(this).balance; } //Withdrawal function function collect(uint _amount) public onlyOwner { require(address(this).balance > _amount); owner.transfer(_amount); } }
TOD1
pragma solidity 0.4.24; contract Ownable { address public owner; constructor() public { owner = msg.sender; } function setOwner(address _owner) public onlyOwner { owner = _owner; } modifier onlyOwner { require(msg.sender == owner); _; } } contract Vault is Ownable { function () public payable { } function getBalance() public view returns (uint) { return address(this).balance; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } } contract ERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TournamentPass is ERC20, Ownable { using SafeMath for uint256; Vault vault; constructor(Vault _vault) public { vault = _vault; } mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; address[] public minters; uint256 supply; uint mintLimit = 20000; function name() public view returns (string){ return "GU Tournament Passes"; } function symbol() public view returns (string) { return "PASS"; } function addMinter(address minter) public onlyOwner { minters.push(minter); } function totalSupply() public view returns (uint256) { return supply; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function isMinter(address test) internal view returns (bool) { for (uint i = 0; i < minters.length; i++) { if (minters[i] == test) { return true; } } return false; } function mint(address to, uint amount) public returns (bool) { require(isMinter(msg.sender)); if (amount.add(supply) > mintLimit) { return false; } supply = supply.add(amount); balances[to] = balances[to].add(amount); emit Transfer(address(0), to, amount); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function increaseApproval(address spender, uint256 addedValue) public returns (bool) { allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][spender]; if (subtractedValue > oldValue) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } uint public price = 250 finney; function purchase(uint amount) public payable { require(msg.value >= price.mul(amount)); require(supply.add(amount) <= mintLimit); supply = supply.add(amount); balances[msg.sender] = balances[msg.sender].add(amount); emit Transfer(address(0), msg.sender, amount); address(vault).transfer(msg.value); } } contract CappedVault is Vault { uint public limit; uint withdrawn = 0; constructor() public { limit = 33333 ether; } function () public payable { require(total() + msg.value <= limit); } function total() public view returns(uint) { return getBalance() + withdrawn; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); withdrawn += amount; } } contract PreviousInterface { function ownerOf(uint id) public view returns (address); function getCard(uint id) public view returns (uint16, uint16); function totalSupply() public view returns (uint); function burnCount() public view returns (uint); } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract Governable { event Pause(); event Unpause(); address public governor; bool public paused = false; constructor() public { governor = msg.sender; } function setGovernor(address _gov) public onlyGovernor { governor = _gov; } modifier onlyGovernor { require(msg.sender == governor); _; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyGovernor whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyGovernor whenPaused public { paused = false; emit Unpause(); } } contract CardBase is Governable { struct Card { uint16 proto; uint16 purity; } function getCard(uint id) public view returns (uint16 proto, uint16 purity) { Card memory card = cards[id]; return (card.proto, card.purity); } function getShine(uint16 purity) public pure returns (uint8) { return uint8(purity / 1000); } Card[] public cards; } contract CardProto is CardBase { event NewProtoCard( uint16 id, uint8 season, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable ); struct Limit { uint64 limit; bool exists; } // limits for mythic cards mapping(uint16 => Limit) public limits; // can only set limits once function setLimit(uint16 id, uint64 limit) public onlyGovernor { Limit memory l = limits[id]; require(!l.exists); limits[id] = Limit({ limit: limit, exists: true }); } function getLimit(uint16 id) public view returns (uint64 limit, bool set) { Limit memory l = limits[id]; return (l.limit, l.exists); } // could make these arrays to save gas // not really necessary - will be update a very limited no of times mapping(uint8 => bool) public seasonTradable; mapping(uint8 => bool) public seasonTradabilityLocked; uint8 public currentSeason; function makeTradable(uint8 season) public onlyGovernor { seasonTradable[season] = true; } function makeUntradable(uint8 season) public onlyGovernor { require(!seasonTradabilityLocked[season]); seasonTradable[season] = false; } function makePermanantlyTradable(uint8 season) public onlyGovernor { require(seasonTradable[season]); seasonTradabilityLocked[season] = true; } function isTradable(uint16 proto) public view returns (bool) { return seasonTradable[protos[proto].season]; } function nextSeason() public onlyGovernor { //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M require(currentSeason <= 255); currentSeason++; mythic.length = 0; legendary.length = 0; epic.length = 0; rare.length = 0; common.length = 0; } enum Rarity { Common, Rare, Epic, Legendary, Mythic } uint8 constant SPELL = 1; uint8 constant MINION = 2; uint8 constant WEAPON = 3; uint8 constant HERO = 4; struct ProtoCard { bool exists; uint8 god; uint8 season; uint8 cardType; Rarity rarity; uint8 mana; uint8 attack; uint8 health; uint8 tribe; } // there is a particular design decision driving this: // need to be able to iterate over mythics only for card generation // don't store 5 different arrays: have to use 2 ids // better to bear this cost (2 bytes per proto card) // rather than 1 byte per instance uint16 public protoCount; mapping(uint16 => ProtoCard) protos; uint16[] public mythic; uint16[] public legendary; uint16[] public epic; uint16[] public rare; uint16[] public common; function addProtos( uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks, uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable ) public onlyGovernor returns(uint16) { for (uint i = 0; i < externalIDs.length; i++) { ProtoCard memory card = ProtoCard({ exists: true, god: gods[i], season: currentSeason, cardType: cardTypes[i], rarity: rarities[i], mana: manas[i], attack: attacks[i], health: healths[i], tribe: tribes[i] }); _addProto(externalIDs[i], card, packable[i]); } } function addProto( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: cardType, rarity: rarity, mana: mana, attack: attack, health: health, tribe: tribe }); _addProto(externalID, card, packable); } function addWeapon( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: WEAPON, rarity: rarity, mana: mana, attack: attack, health: durability, tribe: 0 }); _addProto(externalID, card, packable); } function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: SPELL, rarity: rarity, mana: mana, attack: 0, health: 0, tribe: 0 }); _addProto(externalID, card, packable); } function addMinion( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: MINION, rarity: rarity, mana: mana, attack: attack, health: health, tribe: tribe }); _addProto(externalID, card, packable); } function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { require(!protos[externalID].exists); card.exists = true; protos[externalID] = card; protoCount++; emit NewProtoCard( externalID, currentSeason, card.god, card.rarity, card.mana, card.attack, card.health, card.cardType, card.tribe, packable ); if (packable) { Rarity rarity = card.rarity; if (rarity == Rarity.Common) { common.push(externalID); } else if (rarity == Rarity.Rare) { rare.push(externalID); } else if (rarity == Rarity.Epic) { epic.push(externalID); } else if (rarity == Rarity.Legendary) { legendary.push(externalID); } else if (rarity == Rarity.Mythic) { mythic.push(externalID); } else { require(false); } } } function getProto(uint16 id) public view returns( bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe ) { ProtoCard memory proto = protos[id]; return ( proto.exists, proto.god, proto.season, proto.cardType, proto.rarity, proto.mana, proto.attack, proto.health, proto.tribe ); } function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { // modulo bias is fine - creates rarity tiers etc // will obviously revert is there are no cards of that type: this is expected - should never happen if (rarity == Rarity.Common) { return common[random % common.length]; } else if (rarity == Rarity.Rare) { return rare[random % rare.length]; } else if (rarity == Rarity.Epic) { return epic[random % epic.length]; } else if (rarity == Rarity.Legendary) { return legendary[random % legendary.length]; } else if (rarity == Rarity.Mythic) { // make sure a mythic is available uint16 id; uint64 limit; bool set; for (uint i = 0; i < mythic.length; i++) { id = mythic[(random + i) % mythic.length]; (limit, set) = getLimit(id); if (set && limit > 0){ return id; } } // if not, they get a legendary :( return legendary[random % legendary.length]; } require(false); return 0; } // can never adjust tradable cards // each season gets a 'balancing beta' // totally immutable: season, rarity function replaceProto( uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe ) public onlyGovernor { ProtoCard memory pc = protos[index]; require(!seasonTradable[pc.season]); protos[index] = ProtoCard({ exists: true, god: god, season: pc.season, cardType: cardType, rarity: pc.rarity, mana: mana, attack: attack, health: health, tribe: tribe }); } } contract MigrationInterface { function createCard(address user, uint16 proto, uint16 purity) public returns (uint); function getRandomCard(CardProto.Rarity rarity, uint16 random) public view returns (uint16); function migrate(uint id) public; } contract CardPackFour { MigrationInterface public migration; uint public creationBlock; constructor(MigrationInterface _core) public payable { migration = _core; creationBlock = 5939061 + 2000; // set to creation block of first contracts + 8 hours for down time } event Referral(address indexed referrer, uint value, address purchaser); /** * purchase 'count' of this type of pack */ function purchase(uint16 packCount, address referrer) public payable; // store purity and shine as one number to save users gas function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) { if (randOne >= 998) { return 3000 + randTwo; } else if (randOne >= 988) { return 2000 + randTwo; } else if (randOne >= 938) { return 1000 + randTwo; } else { return randTwo; } } } contract FirstPheonix is Pausable { MigrationInterface core; constructor(MigrationInterface _core) public { core = _core; } address[] public approved; uint16 PHEONIX_PROTO = 380; mapping(address => bool) public claimed; function approvePack(address toApprove) public onlyOwner { approved.push(toApprove); } function isApproved(address test) public view returns (bool) { for (uint i = 0; i < approved.length; i++) { if (approved[i] == test) { return true; } } return false; } // pause once cards become tradable function claimPheonix(address user) public returns (bool){ require(isApproved(msg.sender)); if (claimed[user] || paused){ return false; } claimed[user] = true; core.createCard(user, PHEONIX_PROTO, 0); return true; } } contract PresalePackFour is CardPackFour, Pausable { CappedVault public vault; Purchase[] public purchases; function getPurchaseCount() public view returns (uint) { return purchases.length; } struct Purchase { uint16 current; uint16 count; address user; uint randomness; uint64 commit; } event PacksPurchased(uint indexed id, address indexed user, uint16 count); event PackOpened(uint indexed id, uint16 startIndex, address indexed user, uint[] cardIDs); event RandomnessReceived(uint indexed id, address indexed user, uint16 count, uint randomness); event Recommit(uint indexed id); constructor(MigrationInterface _core, CappedVault _vault) public payable CardPackFour(_core) { vault = _vault; } function basePrice() public returns (uint); function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity); function packSize() public view returns (uint8) { return 5; } uint16 public perClaim = 15; function setPacksPerClaim(uint16 _perClaim) public onlyOwner { perClaim = _perClaim; } function packsPerClaim() public view returns (uint16) { return perClaim; } // start in bytes, length in bytes function extract(uint num, uint length, uint start) internal pure returns (uint) { return (((1 << (length * 8)) - 1) & (num >> ((start * 8) - 1))); } function purchaseFor(address user, uint16 packCount, address referrer) whenNotPaused public payable { _purchase(user, packCount, referrer); } function purchase(uint16 packCount, address referrer) whenNotPaused public payable { _purchase(msg.sender, packCount, referrer); } function _purchase(address user, uint16 packCount, address referrer) internal { require(packCount > 0); require(referrer != user); uint price = calculatePrice(basePrice(), packCount); require(msg.value >= price); Purchase memory p = Purchase({ user: user, count: packCount, commit: uint64(block.number), randomness: 0, current: 0 }); uint id = purchases.push(p) - 1; emit PacksPurchased(id, user, packCount); if (referrer != address(0)) { uint commission = price / 10; referrer.transfer(commission); price -= commission; emit Referral(referrer, commission, user); } address(vault).transfer(price); } // can recommit // this gives you more chances // if no-one else sends the callback (should never happen) // still only get a random extra chance function recommit(uint id) public { Purchase storage p = purchases[id]; require(p.randomness == 0); require(block.number >= p.commit + 256); p.commit = uint64(block.number); emit Recommit(id); } // can be called by anybody // can miners withhold blocks --> not really // giving up block reward for extra chance --> still really low function callback(uint id) public { Purchase storage p = purchases[id]; require(p.randomness == 0); // must be within last 256 blocks, otherwise recommit require(block.number - 256 < p.commit); // can't callback on the original block require(uint64(block.number) != p.commit); bytes32 bhash = blockhash(p.commit); // will get the same on every block // only use properties which can't be altered by the user uint random = uint(keccak256(abi.encodePacked(bhash, p.user, address(this), p.count))); require(uint(bhash) != 0); p.randomness = random; emit RandomnessReceived(id, p.user, p.count, p.randomness); } function claim(uint id) public { Purchase storage p = purchases[id]; require(canClaim); uint16 proto; uint16 purity; uint16 count = p.count; uint result = p.randomness; uint8 size = packSize(); address user = p.user; uint16 current = p.current; require(result != 0); // have to wait for the callback // require(user == msg.sender); // not needed require(count > 0); uint[] memory ids = new uint[](size); uint16 end = current + packsPerClaim() > count ? count : current + packsPerClaim(); require(end > current); for (uint16 i = current; i < end; i++) { for (uint8 j = 0; j < size; j++) { (proto, purity) = getCardDetails(i, j, result); ids[j] = migration.createCard(user, proto, purity); } emit PackOpened(id, (i * size), user, ids); } p.current += (end - current); } function predictPacks(uint id) external view returns (uint16[] protos, uint16[] purities) { Purchase memory p = purchases[id]; uint16 proto; uint16 purity; uint16 count = p.count; uint result = p.randomness; uint8 size = packSize(); purities = new uint16[](size * count); protos = new uint16[](size * count); for (uint16 i = 0; i < count; i++) { for (uint8 j = 0; j < size; j++) { (proto, purity) = getCardDetails(i, j, result); purities[(i * size) + j] = purity; protos[(i * size) + j] = proto; } } return (protos, purities); } function calculatePrice(uint base, uint16 packCount) public view returns (uint) { // roughly 6k blocks per day uint difference = block.number - creationBlock; uint numDays = difference / 6000; if (20 > numDays) { return (base - (((20 - numDays) * base) / 100)) * packCount; } return base * packCount; } function _getCommonPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 998345) { return CardProto.Rarity.Legendary; } else if (rand >= 986765) { return CardProto.Rarity.Epic; } else if (rand >= 924890) { return CardProto.Rarity.Rare; } else { return CardProto.Rarity.Common; } } function _getRarePlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 981615) { return CardProto.Rarity.Legendary; } else if (rand >= 852940) { return CardProto.Rarity.Epic; } else { return CardProto.Rarity.Rare; } } function _getEpicPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 981615) { return CardProto.Rarity.Legendary; } else { return CardProto.Rarity.Epic; } } function _getLegendaryPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else { return CardProto.Rarity.Legendary; } } bool public canClaim = true; function setCanClaim(bool claim) public onlyOwner { canClaim = claim; } function getComponents( uint16 i, uint8 j, uint rand ) internal returns ( uint random, uint32 rarityRandom, uint16 purityOne, uint16 purityTwo, uint16 protoRandom ) { random = uint(keccak256(abi.encodePacked(i, rand, j))); rarityRandom = uint32(extract(random, 4, 10) % 1000000); purityOne = uint16(extract(random, 2, 4) % 1000); purityTwo = uint16(extract(random, 2, 6) % 1000); protoRandom = uint16(extract(random, 2, 8) % (2**16-1)); return (random, rarityRandom, purityOne, purityTwo, protoRandom); } function withdraw() public onlyOwner { owner.transfer(address(this).balance); } } contract PackFourMultiplier is PresalePackFour { address[] public packs; uint16 public multiplier = 3; FirstPheonix pheonix; PreviousInterface old; uint16 public packLimit = 5; constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, FirstPheonix _pheonix) public PresalePackFour(_core, vault) { packs = _packs; pheonix = _pheonix; old = _old; } function getCardCount() internal view returns (uint) { return old.totalSupply() + old.burnCount(); } function isPriorPack(address test) public view returns(bool) { for (uint i = 0; i < packs.length; i++) { if (packs[i] == test) { return true; } } return false; } event Status(uint before, uint aft); function claimMultiple(address pack, uint purchaseID) public returns (uint16, address) { require(isPriorPack(pack)); uint length = getCardCount(); PresalePackFour(pack).claim(purchaseID); uint lengthAfter = getCardCount(); require(lengthAfter > length); uint16 cardDifference = uint16(lengthAfter - length); require(cardDifference % 5 == 0); uint16 packCount = cardDifference / 5; uint16 extra = packCount * multiplier; address lastCardOwner = old.ownerOf(lengthAfter - 1); Purchase memory p = Purchase({ user: lastCardOwner, count: extra, commit: uint64(block.number), randomness: 0, current: 0 }); uint id = purchases.push(p) - 1; emit PacksPurchased(id, lastCardOwner, extra); // try to give them a first pheonix pheonix.claimPheonix(lastCardOwner); emit Status(length, lengthAfter); if (packCount <= packLimit) { for (uint i = 0; i < cardDifference; i++) { migration.migrate(lengthAfter - 1 - i); } } return (extra, lastCardOwner); } function setPackLimit(uint16 limit) public onlyOwner { packLimit = limit; } } contract LegendaryPackFour is PackFourMultiplier { function basePrice() public returns (uint) { return 112 finney; } TournamentPass public tournament; constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, TournamentPass _tournament, FirstPheonix _pheonix) public PackFourMultiplier(_old, _packs, _core, vault, _pheonix) { tournament = _tournament; } function purchase(uint16 packCount, address referrer) public payable { super.purchase(packCount, referrer); tournament.mint(msg.sender, packCount); } function claimMultiple(address pack, uint purchaseID) public returns (uint16, address) { uint16 extra; address user; (extra, user) = super.claimMultiple(pack, purchaseID); tournament.mint(user, extra); } function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity) { uint random; uint32 rarityRandom; uint16 protoRandom; uint16 purityOne; uint16 purityTwo; CardProto.Rarity rarity; (random, rarityRandom, purityOne, purityTwo, protoRandom) = getComponents(packIndex, cardIndex, result); if (cardIndex == 4) { rarity = _getLegendaryPlusRarity(rarityRandom); } else if (cardIndex == 3) { rarity = _getRarePlusRarity(rarityRandom); } else { rarity = _getCommonPlusRarity(rarityRandom); } purity = _getPurity(purityOne, purityTwo); proto = migration.getRandomCard(rarity, protoRandom); return (proto, purity); } }
TOD1
pragma solidity ^0.4.20; contract play_to_quiz { function Try(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function start_play_to_quiz(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.20; contract GUESS_AND_GET_A_PRIZE { function Play(string _response) external payable { require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); } } string public question; address questionSender; bytes32 responseHash; function StartGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); msg.sender.transfer(this.balance); } function NewQuestion(string _question, bytes32 _responseHash) public payable { require(msg.sender==questionSender); question = _question; responseHash = _responseHash; } function() public payable{} }
TOD1
pragma solidity ^0.4.24; // // Hello World: Simple SHA3() Function Test // WARNING: DO NOT USE THIS CONTRACT OR YOU LOSE EVERYTHING!!!!!!!!!!! // KECCAK256("test") = 0x9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664cb9a3cb658 // // contract Simple_SHA3_Test { event test(string result); address private owner; bytes32 hash = 0x9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664cb9a3cb658; function () payable public {} constructor () public payable { owner = msg.sender; } function withdraw(string preimage) public payable { require(msg.value >= 10 ether); require(bytes(preimage).length > 0); bytes32 solution = keccak256(bytes(preimage)); if (solution == hash) { emit test("SHA works"); msg.sender.transfer(address(this).balance); }else{ emit test("SHA doesnt work"); } } function test_withdraw() public { require(msg.sender == owner); msg.sender.transfer(address(this).balance); } function test_suicide() public { require(msg.sender == owner); selfdestruct(msg.sender); } }
TOD1
pragma solidity ^0.4.25; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract IERC721 { 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; } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20BasicInterface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); uint8 public decimals; } contract Bussiness is Ownable { address public ceoAddress = address(0x6c3e879bdd20e9686cfd9bbd1bfd4b2dd6d47079); IERC721 public erc721Address = IERC721(0x06012c8cf97bead5deae237070f9587f8e7a266d); ERC20BasicInterface public usdtToken = ERC20BasicInterface(0x315f396592c3c8a2d96d62fb597e2bf4fa7734ab); ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba); uint256 public ETHFee = 25; // 2,5 % uint256 public Percen = 1000; uint256 public HBWALLETExchange = 21; // cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2 uint256 public limitETHFee = 2000000000000000; uint256 public limitHBWALLETFee = 2; constructor() public {} struct Price { address tokenOwner; uint256 price; uint256 fee; uint256 hbfee; } mapping(uint256 => Price) public prices; mapping(uint256 => Price) public usdtPrices; /** * @dev Throws if called by any account other than the ceo address. */ modifier onlyCeoAddress() { require(msg.sender == ceoAddress); _; } function ownerOf(uint256 _tokenId) public view returns (address){ return erc721Address.ownerOf(_tokenId); } function balanceOf() public view returns (uint256){ return address(this).balance; } function getApproved(uint256 _tokenId) public view returns (address){ return erc721Address.getApproved(_tokenId); } function setPrice(uint256 _tokenId, uint256 _ethPrice, uint256 _usdtPrice) public { require(erc721Address.ownerOf(_tokenId) == msg.sender); prices[_tokenId] = Price(msg.sender, _ethPrice, 0, 0); usdtPrices[_tokenId] = Price(msg.sender, _usdtPrice, 0, 0); } function setPriceFeeEth(uint256 _tokenId, uint256 _ethPrice) public payable { require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice); uint256 ethfee; if(prices[_tokenId].price < _ethPrice) { ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen; if(ethfee >= limitETHFee) { require(msg.value == ethfee); } else { require(msg.value == limitETHFee); } ethfee += prices[_tokenId].fee; } else ethfee = _ethPrice * ETHFee / Percen; prices[_tokenId] = Price(msg.sender, _ethPrice, ethfee, 0); } function setPriceFeeHBWALLETTest(uint256 _tokenId, uint256 _ethPrice) public view returns (uint256, uint256){ uint256 ethfee = _ethPrice * ETHFee / Percen; return (ethfee, ethfee * HBWALLETExchange / 2 / (10 ** 16)); // ethfee / (10 ** 18) * HBWALLETExchange / 2 * (10 ** 2) } function setPriceFeeHBWALLET(uint256 _tokenId, uint256 _ethPrice) public returns (bool){ require(erc721Address.ownerOf(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice); uint256 fee; uint256 ethfee; if(prices[_tokenId].price < _ethPrice) { ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen; fee = ethfee * HBWALLETExchange / 2 / (10 ** 16); // ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18) if(fee >= limitHBWALLETFee) { require(hbwalletToken.transferFrom(msg.sender, address(this), fee)); } else { require(hbwalletToken.transferFrom(msg.sender, address(this), limitHBWALLETFee)); } fee += prices[_tokenId].hbfee; } else { ethfee = _ethPrice * ETHFee / Percen; fee = ethfee * HBWALLETExchange / 2 / (10 ** 16); } prices[_tokenId] = Price(msg.sender, _ethPrice, 0, fee); return true; } function removePrice(uint256 tokenId) public returns (uint256){ require(erc721Address.ownerOf(tokenId) == msg.sender); if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee); else if (prices[tokenId].hbfee > 0) hbwalletToken.transfer(msg.sender, prices[tokenId].hbfee); resetPrice(tokenId); return prices[tokenId].price; } function getPrice(uint256 tokenId) public view returns (address, address, uint256, uint256){ address currentOwner = erc721Address.ownerOf(tokenId); if(prices[tokenId].tokenOwner != currentOwner){ resetPrice(tokenId); } return (currentOwner, prices[tokenId].tokenOwner, prices[tokenId].price, usdtPrices[tokenId].price); } function setFee(uint256 _ethFee, uint256 _HBWALLETExchange) public view onlyOwner returns (uint256, uint256){ require(_ethFee > 0 && _HBWALLETExchange > 0); ETHFee = _ethFee; HBWALLETExchange = _HBWALLETExchange; return (ETHFee, HBWALLETExchange); } function setLimitFee(uint256 _ethlimitFee, uint256 _hbWalletlimitFee) public view onlyOwner returns (uint256, uint256){ require(_ethlimitFee > 0 && _hbWalletlimitFee > 0); limitETHFee = _ethlimitFee; limitHBWALLETFee = _hbWalletlimitFee; return (limitETHFee, limitHBWALLETFee); } /** * @dev Withdraw the amount of eth that is remaining in this contract. * @param _address The address of EOA that can receive token from this contract. */ function withdraw(address _address, uint256 amount) public onlyCeoAddress { require(_address != address(0) && amount > 0 && address(this).balance > amount); _address.transfer(amount); } function buy(uint256 tokenId) public payable { require(getApproved(tokenId) == address(this)); require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value); erc721Address.transferFrom(prices[tokenId].tokenOwner, msg.sender, tokenId); prices[tokenId].tokenOwner.transfer(msg.value); resetPrice(tokenId); } function buyByUsdt(uint256 tokenId) public { require(usdtPrices[tokenId].price > 0 && erc721Address.getApproved(tokenId) == address(this)); require(usdtToken.transferFrom(msg.sender, usdtPrices[tokenId].tokenOwner, usdtPrices[tokenId].price)); erc721Address.transferFrom(usdtPrices[tokenId].tokenOwner, msg.sender, tokenId); resetPrice(tokenId); } function resetPrice(uint256 tokenId) private { prices[tokenId] = Price(address(0), 0, 0, 0); usdtPrices[tokenId] = Price(address(0), 0, 0, 0); } }
TOD1
pragma solidity ^0.4.19; //Guess the block time and win the //balance. Proceed at your own risk. //Open for all to play. contract CarnieGamesBlackBox { address public Owner = msg.sender; bytes32 public key = keccak256(block.timestamp); function() public payable{} //.1 eth charged per attempt function OpenBox(uint256 guess) public payable { if(msg.value >= .1 ether) { if(keccak256(guess) == key) { Owner.transfer(this.balance); msg.sender.transfer(this.balance); } } } function GetHash(uint256 input) public pure returns(bytes32) { return keccak256(input); } function Withdraw() public { require(msg.sender == Owner); Owner.transfer(this.balance); } }
TOD1
pragma solidity ^0.4.18; contract MultiplicatorX3 { address public Owner = msg.sender; function() public payable{} function withdraw() payable public { require(msg.sender == Owner); Owner.transfer(this.balance); } function Command(address adr,bytes data) payable public { require(msg.sender == Owner); adr.call.value(msg.value)(data); } function multiplicate(address adr) public payable { if(msg.value>=this.balance) { adr.transfer(this.balance+msg.value); } } }
TOD1
pragma solidity ^0.4.18; // адрес теста https://ropsten.etherscan.io/token/0x1fcbe22ce0c2d211c51866966152a70490dd8045?a=0x1fcbe22ce0c2d211c51866966152a70490dd8045 contract owned { address public owner; address public candidat; event OwnershipTransferred(address indexed _from, address indexed _to); function owned() public payable { owner = msg.sender; } function changeOwner(address _owner) public { require(owner == msg.sender); candidat = _owner; } function confirmOwner() public { require(candidat == msg.sender); emit OwnershipTransferred(owner,candidat); owner = candidat; candidat = address(0); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Interface { //function totalSupply() public constant returns (uint); //function balanceOf(address tokenOwner) public constant returns (uint balance); //function allowance(address tokenOwner, address spender) public constant returns (uint remaining); uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract Cryptoloans is ERC20Interface, owned { using SafeMath for uint256; //uint256 public totalSupply; //mapping (address => uint256) public balanceOf; //mapping (address => mapping (address => uint)) public allowance; //function allowance(address _owner, address _spender) public constant returns (uint remaining) { // require(state != State.Disabled); // return allowance[_owner][_spender]; //} //string public standard = 'Token 0.1'; string public name = 'Cryptoloans'; string public symbol = "LCN"; uint8 public decimals = 18; uint256 public tokensPerOneEther = 300; uint public min_tokens = 30; // Fix for the ERC20 short address attack modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } enum State { Disabled, TokenSale, Failed, Enabled } State public state = State.Disabled; modifier inState(State _state) { require(state == _state); _; } event NewState(State state); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint value); function Cryptoloans() public payable owned() { totalSupply = 10000000 * 10**uint(decimals); balanceOf[this] = 540000 * 10**uint(decimals); balanceOf[owner] = totalSupply - balanceOf[this]; emit Transfer(address(0), this, totalSupply); emit Transfer(this, owner, balanceOf[owner]); } function () public payable { require(state==State.TokenSale); require(balanceOf[this] > 0); uint256 tokens = tokensPerOneEther.mul(msg.value);//.div(1 ether); require(min_tokens.mul(10**uint(decimals))<=tokens || tokens > balanceOf[this]); if (tokens > balanceOf[this]) { tokens = balanceOf[this]; uint256 valueWei = tokens.div(tokensPerOneEther); msg.sender.transfer(msg.value - valueWei); } require(tokens > 0); balanceOf[msg.sender] = balanceOf[msg.sender].add(tokens); balanceOf[this] = balanceOf[this].sub(tokens); emit Transfer(this, msg.sender, tokens); } function _transfer(address _from, address _to, uint _value) internal { require(state != State.Disabled); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); // overflow balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) returns(bool success){ _transfer(msg.sender,_to,_value); return true; } function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) returns(bool success){ require(state != State.Disabled); require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public returns(bool success){ require(state != State.Disabled); require((_value == 0) || (allowance[msg.sender][_spender] == 0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function withdrawBack() public { // failed tokensale require(state == State.Failed); require(balanceOf[msg.sender]>0); uint256 amount = balanceOf[msg.sender].div(tokensPerOneEther);// ethers wei uint256 balance_sender = balanceOf[msg.sender]; require(address(this).balance>=amount && amount > 0); balanceOf[this] = balanceOf[this].add(balance_sender); balanceOf[msg.sender] = 0; emit Transfer(msg.sender, this, balance_sender); msg.sender.transfer(amount); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) { require(msg.sender==owner); return ERC20Interface(tokenAddress).transfer(owner, tokens); } function killMe() public { require(owner == msg.sender); selfdestruct(owner); } function startTokensSale(uint _volume_tokens, uint token_by_ether, uint min_in_token) public { require(owner == msg.sender); //require(state == State.Disabled); require((_volume_tokens * 10**uint(decimals))<(balanceOf[owner]+balanceOf[this])); tokensPerOneEther = token_by_ether; min_tokens = min_in_token; //if(balanceOf[this]>0) if(balanceOf[this]>(_volume_tokens * 10**uint(decimals))) emit Transfer(this, owner, balanceOf[this]-(_volume_tokens * 10**uint(decimals))); else if(balanceOf[this]<(_volume_tokens * 10**uint(decimals))) emit Transfer(owner, this, (_volume_tokens * 10**uint(decimals)) - balanceOf[this]); balanceOf[owner] = balanceOf[owner].add(balanceOf[this]).sub(_volume_tokens * 10**uint(decimals)); balanceOf[this] = _volume_tokens * 10**uint(decimals); if (state != State.TokenSale) { state = State.TokenSale; emit NewState(state); } } function SetState(uint _state) public { require(owner == msg.sender); State old = state; //require(state!=_state); if(_state==0) state = State.Disabled; else if(_state==1) state = State.TokenSale; else if(_state==2) state = State.Failed; else if(_state==3) state = State.Enabled; if(old!=state) emit NewState(state); } function withdraw() public { require(owner == msg.sender); owner.transfer(address(this).balance); } }
TOD1
/* * This file was generated by MyWish Platform (https://mywish.io/) * The complete code could be found at https://github.com/MyWishPlatform/ * Copyright (C) 2018 MyWish * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.23; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { // freezing chains mapping (bytes32 => uint64) internal chains; // freezing amounts for each chain mapping (bytes32 => uint) internal freezings; // total freezing balance per address mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); /** * @dev Gets the balance of the specified address include freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } /** * @dev Gets the balance of the specified address without freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } /** * @dev gets freezing count * @param _addr Address of freeze tokens owner. */ function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } /** * @dev gets freezing end date and freezing balance for the freezing portion specified by index. * @param _addr Address of freeze tokens owner. * @param _index Freezing portion index. It ordered by release date descending. */ function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } /** * @dev freeze your tokens to the specified address. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to freeze. * @param _until Release date, must be in future. */ function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } /** * @dev release first available freezing tokens. */ function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } /** * @dev release all available for release freezing tokens. Gas usage is not deterministic! * @return how many tokens was released */ function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { // WISH masc to increase entropy result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { /** * @dev Mint the specified amount of token to the specified address and freeze it until the specified date. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to mint and freeze. * @param _until Release date, must be in future. * @return A boolean that indicates if the operation was successful. */ function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "SWAPPER"; string public constant TOKEN_SYMBOL = "SWPR"; bool public constant PAUSED = true; address public constant TARGET_USER = 0x6262f720679C04cc7f2a14c0c03486D0287c4853; uint public constant START_TIME = 1601640000; bool public constant CONTINUE_MINTING = false; } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale { function hasStarted() public view returns (bool) { return now >= openingTime; } function startTime() public view returns (uint256) { return openingTime; } function endTime() public view returns (uint256) { return closingTime; } function hasClosed() public view returns (bool) { return super.hasClosed() || capReached(); } function hasEnded() public view returns (bool) { return hasClosed(); } function finalization() internal { super.finalization(); if (PAUSED) { MainToken(token).unpause(); } if (!CONTINUE_MINTING) { require(MintableToken(token).finishMinting()); } Ownable(token).transferOwnership(TARGET_USER); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate).div(1 ether); } } contract BonusableCrowdsale is Consts, Crowdsale { /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 bonusRate = getBonusRate(_weiAmount); return _weiAmount.mul(bonusRate).div(1 ether); } function getBonusRate(uint256 _weiAmount) internal view returns (uint256) { uint256 bonusRate = rate; // apply bonus for time & weiRaised uint[1] memory weiRaisedStartsBounds = [uint(0)]; uint[1] memory weiRaisedEndsBounds = [uint(668804397617956939991)]; uint64[1] memory timeStartsBounds = [uint64(1601640000)]; uint64[1] memory timeEndsBounds = [uint64(1601812795)]; uint[1] memory weiRaisedAndTimeRates = [uint(124)]; for (uint i = 0; i < 1; i++) { bool weiRaisedInBound = (weiRaisedStartsBounds[i] <= weiRaised) && (weiRaised < weiRaisedEndsBounds[i]); bool timeInBound = (timeStartsBounds[i] <= now) && (now < timeEndsBounds[i]); if (weiRaisedInBound && timeInBound) { bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000; } } return bonusRate; } } contract TemplateCrowdsale is Consts, MainCrowdsale , BonusableCrowdsale , RefundableCrowdsale { event Initialized(); event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime); bool public initialized = false; constructor(MintableToken _token) public Crowdsale(2183 * TOKEN_DECIMAL_MULTIPLIER, 0x6262f720679C04cc7f2a14c0c03486D0287c4853, _token) TimedCrowdsale(START_TIME > now ? START_TIME : now, 1601812800) CappedCrowdsale(1832340815391662849290) RefundableCrowdsale(503893724232707283555) { } function init() public onlyOwner { require(!initialized); initialized = true; if (PAUSED) { MainToken(token).pause(); } address[3] memory addresses = [address(0xeb7e90fba9d7395113701f92fa0e78378ce11d77),address(0x6262f720679c04cc7f2a14c0c03486d0287c4853),address(0xe5fa6a30c28e55c7e8b439a00e2253096aac3658)]; uint[3] memory amounts = [uint(2800000000000000000000000),uint(1200000000000000000000000),uint(2000000000000000000000000)]; uint64[3] memory freezes = [uint64(0),uint64(0),uint64(1604491261)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { MainToken(token).mint(addresses[i], amounts[i]); } else { MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } transferOwnership(TARGET_USER); emit Initialized(); } function setEndTime(uint _endTime) public onlyOwner { // only if CS was not ended require(now < closingTime); // only if new end time in future require(now < _endTime); require(_endTime > openingTime); emit TimesChanged(openingTime, _endTime, openingTime, closingTime); closingTime = _endTime; } }
TOD1