Skip to content

Instantly share code, notes, and snippets.

@rise-worlds
Created September 5, 2018 02:31
Show Gist options
  • Save rise-worlds/0796f5d28794a5d1f1a32b1f3c9c8195 to your computer and use it in GitHub Desktop.
Save rise-worlds/0796f5d28794a5d1f1a32b1f3c9c8195 to your computer and use it in GitHub Desktop.

Revisions

  1. rise-worlds created this gist Sep 5, 2018.
    50 changes: 50 additions & 0 deletions BasicToken.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    pragma solidity ^0.4.24;


    import "./ERC20Basic.sol";
    import "./SafeMath.sol";


    /**
    * @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];
    }

    }
    172 changes: 172 additions & 0 deletions DSMath.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,172 @@
    /// math.sol -- mixin for inline numerical wizardry

    // Copyright (C) 2015, 2016, 2017 DappHub, LLC

    // Licensed under the Apache License, Version 2.0 (the "License").
    // You may not use this file except in compliance with the License.

    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).

    pragma solidity ^0.4.21;

    contract DSMath {

    /*
    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);
    }

    }
    22 changes: 22 additions & 0 deletions DetailedERC20.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    pragma solidity ^0.4.24;

    import "./ERC20.sol";


    /**
    * @title DetailedERC20 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 DetailedERC20 is ERC20 {
    string public name;
    string public symbol;
    uint8 public decimals;

    constructor(string _name, string _symbol, uint8 _decimals) public {
    name = _name;
    symbol = _symbol;
    decimals = _decimals;
    }
    }
    23 changes: 23 additions & 0 deletions ERC20.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    pragma solidity ^0.4.24;

    import "./ERC20Basic.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
    );
    }
    14 changes: 14 additions & 0 deletions ERC20Basic.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    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);
    }
    60 changes: 60 additions & 0 deletions MintableToken.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    pragma solidity ^0.4.24;

    import "./StandardToken.sol";
    import "./Ownable.sol";


    /**
    * @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;
    }
    }
    64 changes: 64 additions & 0 deletions Ownable.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    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;
    }
    }
    21 changes: 21 additions & 0 deletions PotatoToken.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    pragma solidity ^0.4.21;

    import './MintableToken.sol';
    import './DetailedERC20.sol';
    import './Ownable.sol';

    contract PotatoToken is MintableToken, DetailedERC20 {
    uint256 public constant INITIAL_SUPPLY = 0;

    constructor() public DetailedERC20("PotatoToken", "PC", 18) {
    // name = "PotatoToken";
    // symbol = "PC";
    // decimals = 18;
    totalSupply_ = INITIAL_SUPPLY;
    balances[msg.sender] = INITIAL_SUPPLY;
    }

    function totalSupply() public view returns (uint256) {
    return totalSupply_;
    }
    }
    219 changes: 219 additions & 0 deletions PotatoTokenSale.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,219 @@
    pragma solidity ^0.4.21;

    import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
    import './PotatoToken.sol';
    import './DSMath.sol';

    contract PotatoTokenSale is Ownable, DSMath
    {
    bool public closed;
    uint256 public priceInWei;
    PotatoToken public POTATO;
    uint128 public totalSupply; // Total POTATO amount created
    uint128 public foundersAllocation; // Amount given to founders
    string public foundersKey; // Public key of founders

    // uint public openTime; // Time of window 0 opening
    uint public createFirstDay; // Tokens sold in window 0

    uint public startTime; // Time of window 1 opening
    uint public numberOfDays; // Number of windows after 0
    uint public createPerDay; // Tokens sold in each window

    mapping (uint => uint) public dailyTotals;
    mapping (uint => mapping (address => uint)) public userBuys;
    mapping (uint => mapping (address => bool)) public claimed;
    mapping (address => string) public keys;

    event LogBuy (uint window, address user, uint amount);
    event LogClaim (uint window, address user, uint amount);
    event LogRegister (address user, string key);
    event LogCollect (uint amount);
    event LogFreeze ();

    constructor(
    uint _numberOfDays,
    uint128 _totalSupply,
    // uint _openTime,
    // uint _startTime,
    uint128 _foundersAllocation,
    string _foundersKey)
    public
    {
    numberOfDays = _numberOfDays;
    totalSupply = _totalSupply;
    // openTime = _openTime;
    // startTime = _startTime;
    foundersAllocation = _foundersAllocation;
    foundersKey = _foundersKey;

    createFirstDay = wmul(totalSupply, 0.2 ether);
    createPerDay = div(
    sub(sub(totalSupply, foundersAllocation), createFirstDay),
    numberOfDays
    );

    assert(numberOfDays > 0);
    assert(totalSupply > foundersAllocation);
    // assert(openTime < startTime);
    startTime = time();
    }

    function initialize(PotatoToken potato) public onlyOwner
    {
    assert(address(POTATO) == address(0));
    assert(potato.owner() == address(this));
    assert(potato.totalSupply() == 0);

    POTATO = potato;

    POTATO.mint(owner, totalSupply);

    // Address 0xb1 is provably non-transferrable
    // POTATO.push(0xb1, foundersAllocation);
    // POTATO.transfer(0xb1, foundersAllocation);
    POTATO.transferFrom(owner, 0xb1, foundersAllocation);
    keys[0xb1] = foundersKey;
    LogRegister(0xb1, foundersKey);
    }

    function time() public view returns (uint)
    {
    return block.timestamp;
    }

    function today() public view returns (uint)
    {
    return dayFor(time());
    }

    // Each window is 23 hours long so that end-of-window rotates
    // around the clock for all timezones.
    function dayFor(uint timestamp) public view returns (uint)
    {
    return timestamp < startTime
    ? 0
    : sub(timestamp, startTime) / 23 hours + 1;
    }

    function createOnDay(uint day) public view returns (uint)
    {
    return day == 0 ? createFirstDay : createPerDay;
    }

    // This method provides the buyer some protections regarding which
    // day the buy order is submitted and the maximum price prior to
    // applying this payment that will be allowed.
    function buyWithLimit(uint day, uint limit) public payable
    {
    // assert(time() >= openTime && today() <= numberOfDays);
    assert(today() <= numberOfDays);
    assert(msg.value >= 0.01 ether);

    assert(day >= today());
    assert(day <= numberOfDays);

    userBuys[day][msg.sender] += msg.value;
    dailyTotals[day] += msg.value;

    if (limit != 0) {
    assert(dailyTotals[day] <= limit);
    }

    LogBuy(day, msg.sender, msg.value);
    }

    function buy() public payable
    {
    buyWithLimit(today(), 0);
    }

    function () public payable
    {
    buy();
    }

    function claim(uint day) public
    {
    assert(today() > day);

    if (claimed[day][msg.sender] || dailyTotals[day] == 0) {
    return;
    }

    // This will have small rounding errors, but the token is
    // going to be truncated to 8 decimal places or less anyway
    // when launched on its own chain.

    var dailyTotal = cast(dailyTotals[day]);
    var userTotal = cast(userBuys[day][msg.sender]);
    var price = wdiv(cast(createOnDay(day)), dailyTotal);
    var reward = wmul(price, userTotal);

    claimed[day][msg.sender] = true;
    // POTATO.push(msg.sender, reward);
    POTATO.transferFrom(owner, msg.sender, reward);

    LogClaim(day, msg.sender, reward);
    }

    function claimAll() public
    {
    for (uint i = 0; i < today(); i++) {
    claim(i);
    }
    }

    // Value should be a public key. Read full key import policy.
    // Manually registering requires a base58
    // encoded using the STEEM, BTS, or POTATO public key format.
    function register(string key) public
    {
    assert(today() <= numberOfDays + 1);
    assert(bytes(key).length <= 64);

    keys[msg.sender] = key;

    LogRegister(msg.sender, key);
    }

    // Crowdsale owners can collect ETH any number of times
    function collect() public onlyOwner
    {
    assert(today() > 0); // Prevent recycling during window 0
    owner.transfer(address(this).balance);
    LogCollect(this.balance);
    }

    // Anyone can freeze the token 1 day after the sale ends
    function freeze() public
    {
    assert(today() > numberOfDays + 1);
    POTATO.finishMinting();
    LogFreeze();
    }

    function getDailyTotals() public view returns (uint[351] result)
    {
    for (uint i = 0; i < 351; i++)
    {
    result[i] = this.dailyTotals(i);
    }
    }

    function getUserBuys(address user) public view returns (uint[351] result)
    {
    for (uint i = 0; i < 351; i++)
    {
    result[i] = this.userBuys(i, user);
    }
    }

    function getUserClaims(address user) public view returns (bool[351] result)
    {
    for (uint i = 0; i < 351; i++)
    {
    result[i] = this.claimed(i, user);
    }
    }
    }
    52 changes: 52 additions & 0 deletions SafeMath.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    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;
    }
    }
    124 changes: 124 additions & 0 deletions StandardToken.sol
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,124 @@
    pragma solidity ^0.4.24;

    import "./BasicToken.sol";
    import "./ERC20.sol";


    /**
    * @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;
    }

    }