ETH Price: $2,488.43 (+2.12%)

Transaction Decoder

Block:
6500443 at Oct-12-2018 09:35:10 AM +UTC
Transaction Fee:
0.0051 ETH $12.69
Gas Used:
850,000 Gas / 6 Gwei

Account State Difference:

  Address   Before After State Difference Code
0xCBdfF889...20204C2EA
0.04799194006689251 Eth
Nonce: 172
0.04289194006689251 Eth
Nonce: 173
0.0051
(Ethermine)
667.554355410534014759 Eth667.559455410534014759 Eth0.0051

Execution Trace

BancorConverter.quickConvert( _path=[0xEF2463099360a085f1f10b076Ed72Ef625497a06, 0x6e0E0B9aB5f8e5F5F2DE4D34FfE46668FFB37476, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315], _amount=20000000000000000000000, _minReturn=12111467580000000000 )
  • BancorConverterExtensions.CALL( )
  • SHP.transferFrom( _from=0xCBdfF8898767AF6eb9B160B24cB73e420204C2EA, _to=0xF20b9e713A33F61fA38792d2aFaF1cD30339126A, _amount=20000000000000000000000 ) => ( success=False )
    File 1 of 3: BancorConverter
    pragma solidity ^0.4.11;
    
    /*
        Utilities & Common Modifiers
    */
    contract Utils {
        /**
            constructor
        */
        function Utils() {
        }
    
        // verifies that an amount is greater than zero
        modifier greaterThanZero(uint256 _amount) {
            require(_amount > 0);
            _;
        }
    
        // validates an address - currently only checks that it isn't null
        modifier validAddress(address _address) {
            require(_address != 0x0);
            _;
        }
    
        // verifies that the address is different than this contract address
        modifier notThis(address _address) {
            require(_address != address(this));
            _;
        }
    
        // Overflow protected math functions
    
        /**
            @dev returns the sum of _x and _y, asserts if the calculation overflows
    
            @param _x   value 1
            @param _y   value 2
    
            @return sum
        */
        function safeAdd(uint256 _x, uint256 _y) internal constant returns (uint256) {
            uint256 z = _x + _y;
            assert(z >= _x);
            return z;
        }
    
        /**
            @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
    
            @param _x   minuend
            @param _y   subtrahend
    
            @return difference
        */
        function safeSub(uint256 _x, uint256 _y) internal constant returns (uint256) {
            assert(_x >= _y);
            return _x - _y;
        }
    
        /**
            @dev returns the product of multiplying _x by _y, asserts if the calculation overflows
    
            @param _x   factor 1
            @param _y   factor 2
    
            @return product
        */
        function safeMul(uint256 _x, uint256 _y) internal constant returns (uint256) {
            uint256 z = _x * _y;
            assert(_x == 0 || z / _x == _y);
            return z;
        }
    }
    
    /*
        ERC20 Standard Token interface
    */
    contract IERC20Token {
        // these functions aren't abstract since the compiler emits automatically generated getter functions as external
        function name() public constant returns (string) {}
        function symbol() public constant returns (string) {}
        function decimals() public constant returns (uint8) {}
        function totalSupply() public constant returns (uint256) {}
        function balanceOf(address _owner) public constant returns (uint256) { _owner; }
        function allowance(address _owner, address _spender) public constant returns (uint256) { _owner; _spender; }
    
        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);
    }
    
    /*
        Owned contract interface
    */
    contract IOwned {
        // this function isn't abstract since the compiler emits automatically generated getter functions as external
        function owner() public constant returns (address) {}
    
        function transferOwnership(address _newOwner) public;
        function acceptOwnership() public;
    }
    
    /*
        Provides support and utilities for contract ownership
    */
    contract Owned is IOwned {
        address public owner;
        address public newOwner;
    
        event OwnerUpdate(address _prevOwner, address _newOwner);
    
        /**
            @dev constructor
        */
        function Owned() {
            owner = msg.sender;
        }
    
        // allows execution by the owner only
        modifier ownerOnly {
            assert(msg.sender == owner);
            _;
        }
    
        /**
            @dev allows transferring the contract ownership
            the new owner still needs to accept the transfer
            can only be called by the contract owner
    
            @param _newOwner    new contract owner
        */
        function transferOwnership(address _newOwner) public ownerOnly {
            require(_newOwner != owner);
            newOwner = _newOwner;
        }
    
        /**
            @dev used by a new owner to accept an ownership transfer
        */
        function acceptOwnership() public {
            require(msg.sender == newOwner);
            OwnerUpdate(owner, newOwner);
            owner = newOwner;
            newOwner = 0x0;
        }
    }
    
    /*
        Provides support and utilities for contract management
    */
    contract Managed {
        address public manager;
        address public newManager;
    
        event ManagerUpdate(address _prevManager, address _newManager);
    
        /**
            @dev constructor
        */
        function Managed() {
            manager = msg.sender;
        }
    
        // allows execution by the manager only
        modifier managerOnly {
            assert(msg.sender == manager);
            _;
        }
    
        /**
            @dev allows transferring the contract management
            the new manager still needs to accept the transfer
            can only be called by the contract manager
    
            @param _newManager    new contract manager
        */
        function transferManagement(address _newManager) public managerOnly {
            require(_newManager != manager);
            newManager = _newManager;
        }
    
        /**
            @dev used by a new manager to accept a management transfer
        */
        function acceptManagement() public {
            require(msg.sender == newManager);
            ManagerUpdate(manager, newManager);
            manager = newManager;
            newManager = 0x0;
        }
    }
    
    /*
        Token Holder interface
    */
    contract ITokenHolder is IOwned {
        function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
    }
    
    /*
        EIP228 Token Converter interface
    */
    contract ITokenConverter {
        function convertibleTokenCount() public constant returns (uint16);
        function convertibleToken(uint16 _tokenIndex) public constant returns (address);
        function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant returns (uint256);
        function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
        // deprecated, backward compatibility
        function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
    }
    
    /*
        We consider every contract to be a 'token holder' since it's currently not possible
        for a contract to deny receiving tokens.
    
        The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
        the owner to send tokens that were sent to the contract by mistake back to their sender.
    */
    contract TokenHolder is ITokenHolder, Owned, Utils {
        /**
            @dev constructor
        */
        function TokenHolder() {
        }
    
        /**
            @dev withdraws tokens held by the contract and sends them to an account
            can only be called by the owner
    
            @param _token   ERC20 token contract address
            @param _to      account to receive the new amount
            @param _amount  amount to withdraw
        */
        function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
            public
            ownerOnly
            validAddress(_token)
            validAddress(_to)
            notThis(_to)
        {
            assert(_token.transfer(_to, _amount));
        }
    }
    
    /*
        Smart Token interface
    */
    contract ISmartToken is IOwned, IERC20Token {
        function disableTransfers(bool _disable) public;
        function issue(address _to, uint256 _amount) public;
        function destroy(address _from, uint256 _amount) public;
    }
    
    /*
        Bancor Formula interface
    */
    contract IBancorFormula {
        function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public constant returns (uint256);
        function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public constant returns (uint256);
    }
    
    /*
        Bancor Gas Price Limit interface
    */
    contract IBancorGasPriceLimit {
        function gasPrice() public constant returns (uint256) {}
    }
    
    /*
        Bancor Quick Converter interface
    */
    contract IBancorQuickConverter {
        function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
        function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
    }
    
    /*
        Bancor Converter Extensions interface
    */
    contract IBancorConverterExtensions {
        function formula() public constant returns (IBancorFormula) {}
        function gasPriceLimit() public constant returns (IBancorGasPriceLimit) {}
        function quickConverter() public constant returns (IBancorQuickConverter) {}
    }
    
    /*
        The smart token controller is an upgradable part of the smart token that allows
        more functionality as well as fixes for bugs/exploits.
        Once it accepts ownership of the token, it becomes the token's sole controller
        that can execute any of its functions.
    
        To upgrade the controller, ownership must be transferred to a new controller, along with
        any relevant data.
    
        The smart token must be set on construction and cannot be changed afterwards.
        Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access.
    
        Note that the controller can transfer token ownership to a new controller that
        doesn't allow executing any function on the token, for a trustless solution.
        Doing that will also remove the owner's ability to upgrade the controller.
    */
    contract SmartTokenController is TokenHolder {
        ISmartToken public token;   // smart token
    
        /**
            @dev constructor
        */
        function SmartTokenController(ISmartToken _token)
            validAddress(_token)
        {
            token = _token;
        }
    
        // ensures that the controller is the token's owner
        modifier active() {
            assert(token.owner() == address(this));
            _;
        }
    
        // ensures that the controller is not the token's owner
        modifier inactive() {
            assert(token.owner() != address(this));
            _;
        }
    
        /**
            @dev allows transferring the token ownership
            the new owner still need to accept the transfer
            can only be called by the contract owner
    
            @param _newOwner    new token owner
        */
        function transferTokenOwnership(address _newOwner) public ownerOnly {
            token.transferOwnership(_newOwner);
        }
    
        /**
            @dev used by a new owner to accept a token ownership transfer
            can only be called by the contract owner
        */
        function acceptTokenOwnership() public ownerOnly {
            token.acceptOwnership();
        }
    
        /**
            @dev disables/enables token transfers
            can only be called by the contract owner
    
            @param _disable    true to disable transfers, false to enable them
        */
        function disableTokenTransfers(bool _disable) public ownerOnly {
            token.disableTransfers(_disable);
        }
    
        /**
            @dev withdraws tokens held by the token and sends them to an account
            can only be called by the owner
    
            @param _token   ERC20 token contract address
            @param _to      account to receive the new amount
            @param _amount  amount to withdraw
        */
        function withdrawFromToken(IERC20Token _token, address _to, uint256 _amount) public ownerOnly {
            ITokenHolder(token).withdrawTokens(_token, _to, _amount);
        }
    }
    
    /*
        Bancor Converter v0.6
    
        The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves.
    
        ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on
        the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract.
    
        The converter is upgradable (just like any SmartTokenController).
    
        WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits
                 or with very small numbers because of precision loss
    
    
        Open issues:
        - Front-running attacks are currently mitigated by the following mechanisms:
            - minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction
            - gas price limit prevents users from having control over the order of execution
          Other potential solutions might include a commit/reveal based schemes
        - Possibly add getters for the connector fields so that the client won't need to rely on the order in the struct
    */
    contract BancorConverter is ITokenConverter, SmartTokenController, Managed {
        uint32 private constant MAX_WEIGHT = 1000000;
        uint32 private constant MAX_CONVERSION_FEE = 1000000;
    
        struct Connector {
            uint256 virtualBalance;         // connector virtual balance
            uint32 weight;                  // connector weight, represented in ppm, 1-1000000
            bool isVirtualBalanceEnabled;   // true if virtual balance is enabled, false if not
            bool isPurchaseEnabled;         // is purchase of the smart token enabled with the connector, can be set by the owner
            bool isSet;                     // used to tell if the mapping element is defined
        }
    
        string public version = '0.6';
        string public converterType = 'bancor';
    
        IBancorConverterExtensions public extensions;       // bancor converter extensions contract
        IERC20Token[] public connectorTokens;               // ERC20 standard token addresses
        IERC20Token[] public quickBuyPath;                  // conversion path that's used in order to buy the token with ETH
        mapping (address => Connector) public connectors;   // connector token addresses -> connector data
        uint32 private totalConnectorWeight = 0;            // used to efficiently prevent increasing the total connector weight above 100%
        uint32 public maxConversionFee = 0;                 // maximum conversion fee for the lifetime of the contract, represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%)
        uint32 public conversionFee = 0;                    // current conversion fee, represented in ppm, 0...maxConversionFee
        bool public conversionsEnabled = true;              // true if token conversions is enabled, false if not
    
        // triggered when a conversion between two tokens occurs (TokenConverter event)
        event Conversion(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return,
                         uint256 _currentPriceN, uint256 _currentPriceD);
        // triggered when the conversion fee is updated
        event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
    
        /**
            @dev constructor
    
            @param  _token              smart token governed by the converter
            @param  _extensions         address of a bancor converter extensions contract
            @param  _maxConversionFee   maximum conversion fee, represented in ppm
            @param  _connectorToken     optional, initial connector, allows defining the first connector at deployment time
            @param  _connectorWeight    optional, weight for the initial connector
        */
        function BancorConverter(ISmartToken _token, IBancorConverterExtensions _extensions, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight)
            SmartTokenController(_token)
            validAddress(_extensions)
            validMaxConversionFee(_maxConversionFee)
        {
            extensions = _extensions;
            maxConversionFee = _maxConversionFee;
    
            if (address(_connectorToken) != 0x0)
                addConnector(_connectorToken, _connectorWeight, false);
        }
    
        // validates a connector token address - verifies that the address belongs to one of the connector tokens
        modifier validConnector(IERC20Token _address) {
            require(connectors[_address].isSet);
            _;
        }
    
        // validates a token address - verifies that the address belongs to one of the convertible tokens
        modifier validToken(IERC20Token _address) {
            require(_address == token || connectors[_address].isSet);
            _;
        }
    
        // verifies that the gas price is lower than the universal limit
        modifier validGasPrice() {
            assert(tx.gasprice <= extensions.gasPriceLimit().gasPrice());
            _;
        }
    
        // validates maximum conversion fee
        modifier validMaxConversionFee(uint32 _conversionFee) {
            require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE);
            _;
        }
    
        // validates conversion fee
        modifier validConversionFee(uint32 _conversionFee) {
            require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
            _;
        }
    
        // validates connector weight range
        modifier validConnectorWeight(uint32 _weight) {
            require(_weight > 0 && _weight <= MAX_WEIGHT);
            _;
        }
    
        // validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
        modifier validConversionPath(IERC20Token[] _path) {
            require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
            _;
        }
    
        // allows execution only when conversions aren't disabled
        modifier conversionsAllowed {
            assert(conversionsEnabled);
            _;
        }
    
        /**
            @dev returns the number of connector tokens defined
    
            @return number of connector tokens
        */
        function connectorTokenCount() public constant returns (uint16) {
            return uint16(connectorTokens.length);
        }
    
        /**
            @dev returns the number of convertible tokens supported by the contract
            note that the number of convertible tokens is the number of connector token, plus 1 (that represents the smart token)
    
            @return number of convertible tokens
        */
        function convertibleTokenCount() public constant returns (uint16) {
            return connectorTokenCount() + 1;
        }
    
        /**
            @dev given a convertible token index, returns its contract address
    
            @param _tokenIndex  convertible token index
    
            @return convertible token address
        */
        function convertibleToken(uint16 _tokenIndex) public constant returns (address) {
            if (_tokenIndex == 0)
                return token;
            return connectorTokens[_tokenIndex - 1];
        }
    
        /*
            @dev allows the owner to update the extensions contract address
    
            @param _extensions    address of a bancor converter extensions contract
        */
        function setExtensions(IBancorConverterExtensions _extensions)
            public
            ownerOnly
            validAddress(_extensions)
            notThis(_extensions)
        {
            extensions = _extensions;
        }
    
        /*
            @dev allows the manager to update the quick buy path
    
            @param _path    new quick buy path, see conversion path format in the BancorQuickConverter contract
        */
        function setQuickBuyPath(IERC20Token[] _path)
            public
            ownerOnly
            validConversionPath(_path)
        {
            quickBuyPath = _path;
        }
    
        /*
            @dev allows the manager to clear the quick buy path
        */
        function clearQuickBuyPath() public ownerOnly {
            quickBuyPath.length = 0;
        }
    
        /**
            @dev returns the length of the quick buy path array
    
            @return quick buy path length
        */
        function getQuickBuyPathLength() public constant returns (uint256) {
            return quickBuyPath.length;
        }
    
        /**
            @dev disables the entire conversion functionality
            this is a safety mechanism in case of a emergency
            can only be called by the manager
    
            @param _disable true to disable conversions, false to re-enable them
        */
        function disableConversions(bool _disable) public managerOnly {
            conversionsEnabled = !_disable;
        }
    
        /**
            @dev updates the current conversion fee
            can only be called by the manager
    
            @param _conversionFee new conversion fee, represented in ppm
        */
        function setConversionFee(uint32 _conversionFee)
            public
            managerOnly
            validConversionFee(_conversionFee)
        {
            ConversionFeeUpdate(conversionFee, _conversionFee);
            conversionFee = _conversionFee;
        }
    
        /*
            @dev returns the conversion fee amount for a given return amount
    
            @return conversion fee amount
        */
        function getConversionFeeAmount(uint256 _amount) public constant returns (uint256) {
            return safeMul(_amount, conversionFee) / MAX_CONVERSION_FEE;
        }
    
        /**
            @dev defines a new connector for the token
            can only be called by the owner while the converter is inactive
    
            @param _token                  address of the connector token
            @param _weight                 constant connector weight, represented in ppm, 1-1000000
            @param _enableVirtualBalance   true to enable virtual balance for the connector, false to disable it
        */
        function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)
            public
            ownerOnly
            inactive
            validAddress(_token)
            notThis(_token)
            validConnectorWeight(_weight)
        {
            require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input
    
            connectors[_token].virtualBalance = 0;
            connectors[_token].weight = _weight;
            connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance;
            connectors[_token].isPurchaseEnabled = true;
            connectors[_token].isSet = true;
            connectorTokens.push(_token);
            totalConnectorWeight += _weight;
        }
    
        /**
            @dev updates one of the token connectors
            can only be called by the owner
    
            @param _connectorToken         address of the connector token
            @param _weight                 constant connector weight, represented in ppm, 1-1000000
            @param _enableVirtualBalance   true to enable virtual balance for the connector, false to disable it
            @param _virtualBalance         new connector's virtual balance
        */
        function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance)
            public
            ownerOnly
            validConnector(_connectorToken)
            validConnectorWeight(_weight)
        {
            Connector storage connector = connectors[_connectorToken];
            require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input
    
            totalConnectorWeight = totalConnectorWeight - connector.weight + _weight;
            connector.weight = _weight;
            connector.isVirtualBalanceEnabled = _enableVirtualBalance;
            connector.virtualBalance = _virtualBalance;
        }
    
        /**
            @dev disables purchasing with the given connector token in case the connector token got compromised
            can only be called by the owner
            note that selling is still enabled regardless of this flag and it cannot be disabled by the owner
    
            @param _connectorToken  connector token contract address
            @param _disable         true to disable the token, false to re-enable it
        */
        function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable)
            public
            ownerOnly
            validConnector(_connectorToken)
        {
            connectors[_connectorToken].isPurchaseEnabled = !_disable;
        }
    
        /**
            @dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance
    
            @param _connectorToken  connector token contract address
    
            @return connector balance
        */
        function getConnectorBalance(IERC20Token _connectorToken)
            public
            constant
            validConnector(_connectorToken)
            returns (uint256)
        {
            Connector storage connector = connectors[_connectorToken];
            return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this);
        }
    
        /**
            @dev returns the expected return for converting a specific amount of _fromToken to _toToken
    
            @param _fromToken  ERC20 token to convert from
            @param _toToken    ERC20 token to convert to
            @param _amount     amount to convert, in fromToken
    
            @return expected conversion return amount
        */
        function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant returns (uint256) {
            require(_fromToken != _toToken); // validate input
    
            // conversion between the token and one of its connectors
            if (_toToken == token)
                return getPurchaseReturn(_fromToken, _amount);
            else if (_fromToken == token)
                return getSaleReturn(_toToken, _amount);
    
            // conversion between 2 connectors
            uint256 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount);
            return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount));
        }
    
        /**
            @dev returns the expected return for buying the token for a connector token
    
            @param _connectorToken  connector token contract address
            @param _depositAmount   amount to deposit (in the connector token)
    
            @return expected purchase return amount
        */
        function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
            public
            constant
            active
            validConnector(_connectorToken)
            returns (uint256)
        {
            Connector storage connector = connectors[_connectorToken];
            require(connector.isPurchaseEnabled); // validate input
    
            uint256 tokenSupply = token.totalSupply();
            uint256 connectorBalance = getConnectorBalance(_connectorToken);
            uint256 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);
    
            // deduct the fee from the return amount
            uint256 feeAmount = getConversionFeeAmount(amount);
            return safeSub(amount, feeAmount);
        }
    
        /**
            @dev returns the expected return for selling the token for one of its connector tokens
    
            @param _connectorToken  connector token contract address
            @param _sellAmount      amount to sell (in the smart token)
    
            @return expected sale return amount
        */
        function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public constant returns (uint256) {
            return getSaleReturn(_connectorToken, _sellAmount, token.totalSupply());
        }
    
        /**
            @dev converts a specific amount of _fromToken to _toToken
    
            @param _fromToken  ERC20 token to convert from
            @param _toToken    ERC20 token to convert to
            @param _amount     amount to convert, in fromToken
            @param _minReturn  if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
    
            @return conversion return amount
        */
        function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
            require(_fromToken != _toToken); // validate input
    
            // conversion between the token and one of its connectors
            if (_toToken == token)
                return buy(_fromToken, _amount, _minReturn);
            else if (_fromToken == token)
                return sell(_toToken, _amount, _minReturn);
    
            // conversion between 2 connectors
            uint256 purchaseAmount = buy(_fromToken, _amount, 1);
            return sell(_toToken, purchaseAmount, _minReturn);
        }
    
        /**
            @dev buys the token by depositing one of its connector tokens
    
            @param _connectorToken  connector token contract address
            @param _depositAmount   amount to deposit (in the connector token)
            @param _minReturn       if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
    
            @return buy return amount
        */
        function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn)
            public
            conversionsAllowed
            validGasPrice
            greaterThanZero(_minReturn)
            returns (uint256)
        {
            uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);
            assert(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
    
            // update virtual balance if relevant
            Connector storage connector = connectors[_connectorToken];
            if (connector.isVirtualBalanceEnabled)
                connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);
    
            // transfer _depositAmount funds from the caller in the connector token
            assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
            // issue new funds to the caller in the smart token
            token.issue(msg.sender, amount);
    
            dispatchConversionEvent(_connectorToken, _depositAmount, amount, true);
            return amount;
        }
    
        /**
            @dev sells the token by withdrawing from one of its connector tokens
    
            @param _connectorToken  connector token contract address
            @param _sellAmount      amount to sell (in the smart token)
            @param _minReturn       if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero
    
            @return sell return amount
        */
        function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn)
            public
            conversionsAllowed
            validGasPrice
            greaterThanZero(_minReturn)
            returns (uint256)
        {
            require(_sellAmount <= token.balanceOf(msg.sender)); // validate input
    
            uint256 amount = getSaleReturn(_connectorToken, _sellAmount);
            assert(amount != 0 && amount >= _minReturn); // ensure the trade gives something in return and meets the minimum requested amount
    
            uint256 tokenSupply = token.totalSupply();
            uint256 connectorBalance = getConnectorBalance(_connectorToken);
            // ensure that the trade will only deplete the connector if the total supply is depleted as well
            assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply));
    
            // update virtual balance if relevant
            Connector storage connector = connectors[_connectorToken];
            if (connector.isVirtualBalanceEnabled)
                connector.virtualBalance = safeSub(connector.virtualBalance, amount);
    
            // destroy _sellAmount from the caller's balance in the smart token
            token.destroy(msg.sender, _sellAmount);
            // transfer funds to the caller in the connector token
            // the transfer might fail if the actual connector balance is smaller than the virtual balance
            assert(_connectorToken.transfer(msg.sender, amount));
    
            dispatchConversionEvent(_connectorToken, _sellAmount, amount, false);
            return amount;
        }
    
        /**
            @dev converts the token to any other token in the bancor network by following a predefined conversion path
            note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand
    
            @param _path        conversion path, see conversion path format in the BancorQuickConverter contract
            @param _amount      amount to convert from (in the initial source token)
            @param _minReturn   if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
    
            @return tokens issued in return
        */
        function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn)
            public
            payable
            validConversionPath(_path)
            returns (uint256)
        {
            IERC20Token fromToken = _path[0];
            IBancorQuickConverter quickConverter = extensions.quickConverter();
    
            // we need to transfer the source tokens from the caller to the quick converter,
            // so it can execute the conversion on behalf of the caller
            if (msg.value == 0) {
                // not ETH, send the source tokens to the quick converter
                // if the token is the smart token, no allowance is required - destroy the tokens from the caller and issue them to the quick converter
                if (fromToken == token) {
                    token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token
                    token.issue(quickConverter, _amount); // issue _amount new tokens to the quick converter
                }
                else {
                    // otherwise, we assume we already have allowance, transfer the tokens directly to the quick converter
                    assert(fromToken.transferFrom(msg.sender, quickConverter, _amount));
                }
            }
    
            // execute the conversion and pass on the ETH with the call
            return quickConverter.convertFor.value(msg.value)(_path, _amount, _minReturn, msg.sender);
        }
    
        // deprecated, backward compatibility
        function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
            return convert(_fromToken, _toToken, _amount, _minReturn);
        }
    
        /**
            @dev utility, returns the expected return for selling the token for one of its connector tokens, given a total supply override
    
            @param _connectorToken  connector token contract address
            @param _sellAmount      amount to sell (in the smart token)
            @param _totalSupply     total token supply, overrides the actual token total supply when calculating the return
    
            @return sale return amount
        */
        function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _totalSupply)
            private
            constant
            active
            validConnector(_connectorToken)
            greaterThanZero(_totalSupply)
            returns (uint256)
        {
            Connector storage connector = connectors[_connectorToken];
            uint256 connectorBalance = getConnectorBalance(_connectorToken);
            uint256 amount = extensions.formula().calculateSaleReturn(_totalSupply, connectorBalance, connector.weight, _sellAmount);
    
            // deduct the fee from the return amount
            uint256 feeAmount = getConversionFeeAmount(amount);
            return safeSub(amount, feeAmount);
        }
    
        /**
            @dev helper, dispatches the Conversion event
            The function also takes the tokens' decimals into account when calculating the current price
    
            @param _connectorToken  connector token contract address
            @param _amount          amount purchased/sold (in the source token)
            @param _returnAmount    amount returned (in the target token)
            @param isPurchase       true if it's a purchase, false if it's a sale
        */
        function dispatchConversionEvent(IERC20Token _connectorToken, uint256 _amount, uint256 _returnAmount, bool isPurchase) private {
            Connector storage connector = connectors[_connectorToken];
    
            // calculate the new price using the simple price formula
            // price = connector balance / (supply * weight)
            // weight is represented in ppm, so multiplying by 1000000
            uint256 connectorAmount = safeMul(getConnectorBalance(_connectorToken), MAX_WEIGHT);
            uint256 tokenAmount = safeMul(token.totalSupply(), connector.weight);
    
            // normalize values
            uint8 tokenDecimals = token.decimals();
            uint8 connectorTokenDecimals = _connectorToken.decimals();
            if (tokenDecimals != connectorTokenDecimals) {
                if (tokenDecimals > connectorTokenDecimals)
                    connectorAmount = safeMul(connectorAmount, 10 ** uint256(tokenDecimals - connectorTokenDecimals));
                else
                    tokenAmount = safeMul(tokenAmount, 10 ** uint256(connectorTokenDecimals - tokenDecimals));
            }
    
            if (isPurchase)
                Conversion(_connectorToken, token, msg.sender, _amount, _returnAmount, connectorAmount, tokenAmount);
            else
                Conversion(token, _connectorToken, msg.sender, _amount, _returnAmount, tokenAmount, connectorAmount);
        }
    
        /**
            @dev fallback, buys the smart token with ETH
            note that the purchase will use the price at the time of the purchase
        */
        function() payable {
            quickConvert(quickBuyPath, msg.value, 1);
        }
    }

    File 2 of 3: BancorConverterExtensions
    pragma solidity ^0.4.11;
    
    /*
        Utilities & Common Modifiers
    */
    contract Utils {
        /**
            constructor
        */
        function Utils() {
        }
    
        // verifies that an amount is greater than zero
        modifier greaterThanZero(uint256 _amount) {
            require(_amount > 0);
            _;
        }
    
        // validates an address - currently only checks that it isn't null
        modifier validAddress(address _address) {
            require(_address != 0x0);
            _;
        }
    
        // verifies that the address is different than this contract address
        modifier notThis(address _address) {
            require(_address != address(this));
            _;
        }
    
        // Overflow protected math functions
    
        /**
            @dev returns the sum of _x and _y, asserts if the calculation overflows
    
            @param _x   value 1
            @param _y   value 2
    
            @return sum
        */
        function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
            uint256 z = _x + _y;
            assert(z >= _x);
            return z;
        }
    
        /**
            @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
    
            @param _x   minuend
            @param _y   subtrahend
    
            @return difference
        */
        function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
            assert(_x >= _y);
            return _x - _y;
        }
    
        /**
            @dev returns the product of multiplying _x by _y, asserts if the calculation overflows
    
            @param _x   factor 1
            @param _y   factor 2
    
            @return product
        */
        function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
            uint256 z = _x * _y;
            assert(_x == 0 || z / _x == _y);
            return z;
        }
    }
    
    /*
        Owned contract interface
    */
    contract IOwned {
        // this function isn't abstract since the compiler emits automatically generated getter functions as external
        function owner() public constant returns (address) {}
    
        function transferOwnership(address _newOwner) public;
        function acceptOwnership() public;
    }
    
    /*
        Provides support and utilities for contract ownership
    */
    contract Owned is IOwned {
        address public owner;
        address public newOwner;
    
        event OwnerUpdate(address _prevOwner, address _newOwner);
    
        /**
            @dev constructor
        */
        function Owned() {
            owner = msg.sender;
        }
    
        // allows execution by the owner only
        modifier ownerOnly {
            assert(msg.sender == owner);
            _;
        }
    
        /**
            @dev allows transferring the contract ownership
            the new owner still needs to accept the transfer
            can only be called by the contract owner
    
            @param _newOwner    new contract owner
        */
        function transferOwnership(address _newOwner) public ownerOnly {
            require(_newOwner != owner);
            newOwner = _newOwner;
        }
    
        /**
            @dev used by a new owner to accept an ownership transfer
        */
        function acceptOwnership() public {
            require(msg.sender == newOwner);
            OwnerUpdate(owner, newOwner);
            owner = newOwner;
            newOwner = 0x0;
        }
    }
    
    /*
        ERC20 Standard Token interface
    */
    contract IERC20Token {
        // these functions aren't abstract since the compiler emits automatically generated getter functions as external
        function name() public constant returns (string) {}
        function symbol() public constant returns (string) {}
        function decimals() public constant returns (uint8) {}
        function totalSupply() public constant returns (uint256) {}
        function balanceOf(address _owner) public constant returns (uint256) { _owner; }
        function allowance(address _owner, address _spender) public constant returns (uint256) { _owner; _spender; }
    
        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);
    }
    
    /*
        Bancor Formula interface
    */
    contract IBancorFormula {
        function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public constant returns (uint256);
        function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public constant returns (uint256);
    }
    
    /*
        Bancor Gas Price Limit interface
    */
    contract IBancorGasPriceLimit {
        function gasPrice() public constant returns (uint256) {}
    }
    
    /*
        Bancor Quick Converter interface
    */
    contract IBancorQuickConverter {
        function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
        function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
    }
    
    /*
        Token Holder interface
    */
    contract ITokenHolder is IOwned {
        function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
    }
    
    /*
        We consider every contract to be a 'token holder' since it's currently not possible
        for a contract to deny receiving tokens.
    
        The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
        the owner to send tokens that were sent to the contract by mistake back to their sender.
    */
    contract TokenHolder is ITokenHolder, Owned, Utils {
        /**
            @dev constructor
        */
        function TokenHolder() {
        }
    
        /**
            @dev withdraws tokens held by the contract and sends them to an account
            can only be called by the owner
    
            @param _token   ERC20 token contract address
            @param _to      account to receive the new amount
            @param _amount  amount to withdraw
        */
        function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
            public
            ownerOnly
            validAddress(_token)
            validAddress(_to)
            notThis(_to)
        {
            assert(_token.transfer(_to, _amount));
        }
    }
    
    /*
        Bancor Converter Extensions interface
    */
    contract IBancorConverterExtensions {
        function formula() public constant returns (IBancorFormula) {}
        function gasPriceLimit() public constant returns (IBancorGasPriceLimit) {}
        function quickConverter() public constant returns (IBancorQuickConverter) {}
    }
    
    /**
        @dev the BancorConverterExtensions contract is an owned contract that serves as a single point of access
        to the BancorFormula, BancorGasPriceLimit and BancorQuickConverter contracts from all BancorConverter contract instances.
        it allows upgrading these contracts without the need to update each and every
        BancorConverter contract instance individually.
    */
    contract BancorConverterExtensions is IBancorConverterExtensions, TokenHolder {
        IBancorFormula public formula;  // bancor calculation formula contract
        IBancorGasPriceLimit public gasPriceLimit; // bancor universal gas price limit contract
        IBancorQuickConverter public quickConverter; // bancor quick converter contract
    
        /**
            @dev constructor
    
            @param _formula         address of a bancor formula contract
            @param _gasPriceLimit   address of a bancor gas price limit contract
            @param _quickConverter  address of a bancor quick converter contract
        */
        function BancorConverterExtensions(IBancorFormula _formula, IBancorGasPriceLimit _gasPriceLimit, IBancorQuickConverter _quickConverter)
            validAddress(_formula)
            validAddress(_gasPriceLimit)
            validAddress(_quickConverter)
        {
            formula = _formula;
            gasPriceLimit = _gasPriceLimit;
            quickConverter = _quickConverter;
        }
    
        /*
            @dev allows the owner to update the formula contract address
    
            @param _formula    address of a bancor formula contract
        */
        function setFormula(IBancorFormula _formula)
            public
            ownerOnly
            validAddress(_formula)
            notThis(_formula)
        {
            formula = _formula;
        }
    
        /*
            @dev allows the owner to update the gas price limit contract address
    
            @param _gasPriceLimit   address of a bancor gas price limit contract
        */
        function setGasPriceLimit(IBancorGasPriceLimit _gasPriceLimit)
            public
            ownerOnly
            validAddress(_gasPriceLimit)
            notThis(_gasPriceLimit)
        {
            gasPriceLimit = _gasPriceLimit;
        }
    
        /*
            @dev allows the owner to update the quick converter contract address
    
            @param _quickConverter  address of a bancor quick converter contract
        */
        function setQuickConverter(IBancorQuickConverter _quickConverter)
            public
            ownerOnly
            validAddress(_quickConverter)
            notThis(_quickConverter)
        {
            quickConverter = _quickConverter;
        }
    }

    File 3 of 3: SHP
    pragma solidity 0.4.15;
    
    
    /// @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;
        }
    }
    
    contract SHP is MiniMeToken {
        // @dev SHP constructor
        function SHP(address _tokenFactory)
                MiniMeToken(
                    _tokenFactory,
                    0x0,                             // no parent token
                    0,                               // no snapshot block number from parent
                    "Sharpe Platform Token",         // Token name
                    18,                              // Decimals
                    "SHP",                           // Symbol
                    true                             // Enable transfers
                ) {}
    }