ETH Price: $2,069.24 (-4.35%)

Transaction Decoder

Block:
5302136 at Mar-22-2018 04:29:14 PM +UTC
Transaction Fee:
0.004 ETH $8.28
Gas Used:
1,000,000 Gas / 4 Gwei

Account State Difference:

  Address   Before After State Difference Code
(Nanopool)
4,841.301369883285249004 Eth4,841.305369883285249004 Eth0.004
0xDe877E66...6EB1d016B
0.040587624 Eth
Nonce: 4
0.036587624 Eth
Nonce: 5
0.004

Execution Trace

BancorConverter.quickConvert( _path=[0xF6B55acBBC49f4524Aa48D19281A9A77c54DE10f, 0xd387CDAF85429b455f0F716D51Be33db2FC00463, 0xd387CDAF85429b455f0F716D51Be33db2FC00463, 0xd387CDAF85429b455f0F716D51Be33db2FC00463, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0xa7774F9386E1653645E1A08fb7Aae525B4DeDb24, 0xa7774F9386E1653645E1A08fb7Aae525B4DeDb24, 0xa7774F9386E1653645E1A08fb7Aae525B4DeDb24, 0x419c4dB4B9e25d6Db2AD9691ccb832C8D9fDA05E], _amount=1000000000000000000000, _minReturn=251862156658243400000 )
  • BancorConverterExtensions.CALL( )
  • WolkExchange.transferFrom( _from=0xDe877E6628D8167e6b29977f65c017e6EB1d016B, _to=0xF87a7EC94884F44D9dE33d36b73F42c7c0Dd38B1, _value=1000000000000000000000 ) => ( 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: WolkExchange
    pragma solidity ^0.4.16;
    
    // SafeMath Taken From FirstBlood
    contract SafeMath {
        function safeMul(uint a, uint b) internal returns (uint) {
            uint c = a * b;
            assert(a == 0 || c / a == b);
            return c;
        }
    
        function safeDiv(uint a, uint b) internal returns (uint) {
            assert(b > 0);
            uint c = a / b;
            assert(a == b * c + a % b);
            return c;
        }
    
        function safeSub(uint a, uint b) internal returns (uint) {
            assert(b <= a);
            return a - b;
        }
    
        function safeAdd(uint a, uint b) internal returns (uint) {
            uint c = a + b;
            assert(c>=a && c>=b);
            return c;
        }
    }
    
    // Ownership
    contract Owned {
    
        address public owner;
        address public newOwner;
        modifier onlyOwner { assert(msg.sender == owner); _; }
    
        event OwnerUpdate(address _prevOwner, address _newOwner);
    
        function Owned() {
            owner = msg.sender;
        }
    
        function transferOwnership(address _newOwner) public onlyOwner {
            require(_newOwner != owner);
            newOwner = _newOwner;
        }
    
        function acceptOwnership() public {
            require(msg.sender == newOwner);
            OwnerUpdate(owner, newOwner);
            owner = newOwner;
            newOwner = 0x0;
        }
    }
    
    // ERC20 Interface
    contract ERC20 {
        function totalSupply() constant returns (uint _totalSupply);
        function balanceOf(address _owner) constant returns (uint balance);
        function transfer(address _to, uint _value) returns (bool success);
        function transferFrom(address _from, address _to, uint _value) returns (bool success);
        function approve(address _spender, uint _value) returns (bool success);
        function allowance(address _owner, address _spender) constant returns (uint remaining);
        event Transfer(address indexed _from, address indexed _to, uint _value);
        event Approval(address indexed _owner, address indexed _spender, uint _value);
    }
    
    // ERC20Token
    contract ERC20Token is ERC20, SafeMath {
    
        mapping(address => uint256) balances;
        mapping (address => mapping (address => uint256)) allowed;
        uint256 public totalTokens; 
        uint256 public contributorTokens; 
    
        function transfer(address _to, uint256 _value) returns (bool success) {
            if (balances[msg.sender] >= _value && _value > 0) {
                balances[msg.sender] = safeSub(balances[msg.sender], _value);
                balances[_to] = safeAdd(balances[_to], _value);
                Transfer(msg.sender, _to, _value);
                return true;
            } else {
                return false;
            }
        }
    
        function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
            var _allowance = allowed[_from][msg.sender];
            if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
                balances[_to] = safeAdd(balances[_to], _value);
                balances[_from] = safeSub(balances[_from], _value);
                allowed[_from][msg.sender] = safeSub(_allowance, _value);
                Transfer(_from, _to, _value);
                return true;
            } else {
                return false;
            }
        }
    
        function totalSupply() constant returns (uint256) {
            return totalTokens;
        }
    
        function balanceOf(address _owner) constant returns (uint256 balance) {
            return balances[_owner];
        }
    
        function approve(address _spender, uint256 _value) returns (bool success) {
            require((_value == 0) || (allowed[msg.sender][_spender] == 0));
            allowed[msg.sender][_spender] = _value;
            Approval(msg.sender, _spender, _value);
            return true;
        }
    
        function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
            return allowed[_owner][_spender];
        }
    
    }
    
    contract Wolk is ERC20Token, Owned {
    
        // TOKEN INFO
        string  public constant name = "WOLK TOKEN";
        string  public constant symbol = "WLK";
        uint256 public constant decimals = 18;
    
        // RESERVE
        uint256 public reserveBalance = 0; 
        uint8   public percentageETHReserve = 5;
    
        // CONTRACT OWNER
        address public wolkInc;
    
        // TOKEN GENERATION CONTROL
        bool    public allSaleCompleted = false;
    
        modifier isTransferable { require(allSaleCompleted); _; }
    
        // TOKEN GENERATION EVENTLOG
        event WolkCreated(address indexed _to, uint256 _tokenCreated);
        event WolkDestroyed(address indexed _from, uint256 _tokenDestroyed);
        event LogRefund(address indexed _to, uint256 _value);
    }
    
    contract WolkTGE is Wolk {
    
        // TOKEN GENERATION EVENT
        mapping (address => uint256) contribution;
        mapping (address => bool) whitelistContributor;
        
        uint256 public constant tokenGenerationMin =   1 * 10**4 * 10**decimals;
        uint256 public constant tokenGenerationMax = 175 * 10**5 * 10**decimals;
        uint256 public start_block;
        uint256 public end_time;
        bool    kycRequirement = true;
    
        // @param _startBlock
        // @param _endTime
        // @param _wolkinc - wolk inc tokens sent here
        // @return success
        // @dev Wolk Genesis Event [only accessible by Contract Owner]
        function wolkGenesis(uint256 _startBlock, uint256 _endTime, address _wolkinc) onlyOwner returns (bool success){
            require((totalTokens < 1) && (block.number <= _startBlock)); 
            start_block = _startBlock;
            end_time = _endTime;
            wolkInc = _wolkinc;
            return true;
        }
        
        // @param _participants
        // @return success
        function updateRequireKYC(bool _kycRequirement) onlyOwner returns (bool success) {
            kycRequirement = _kycRequirement;
            return true;
        } 
        
        // @param _participants
        // @return success
        function addParticipant(address[] _participants) onlyOwner returns (bool success) {
            for (uint cnt = 0; cnt < _participants.length; cnt++){           
                whitelistContributor[_participants[cnt]] = true;
            }
            return true;
        } 
    
        // @param _participants
        // @return success
        // @dev Revoke designated contributors [only accessible by current Contract Owner]
        function removeParticipant(address[] _participants) onlyOwner returns (bool success){         
            for (uint cnt = 0; cnt < _participants.length; cnt++){           
                whitelistContributor[_participants[cnt]] = false;
            }
            return true;
        }
    
        // @param _participant
        // @return status
        // @dev return status of given address
        function participantStatus(address _participant) constant returns (bool status) {
            return(whitelistContributor[_participant]);
        }    
    
        // @param _participant
        // @dev use tokenGenerationEvent to handle sale of WOLK
        function tokenGenerationEvent(address _participant) payable external {
            require( ( whitelistContributor[_participant] || whitelistContributor[msg.sender] || balances[_participant] > 0 || kycRequirement )  && !allSaleCompleted && ( block.timestamp <= end_time ) && msg.value > 0);
        
            uint256 rate = 1000;  // Default Rate
            rate = safeDiv( 175 * 10**5 * 10**decimals, safeAdd( 875 * 10**1 * 10**decimals, safeDiv( totalTokens, 2 * 10**3)) );
            if ( rate > 2000 ) rate = 2000;
            if ( rate < 500 ) rate = 500;
            require(block.number >= start_block) ;
    
            uint256 tokens = safeMul(msg.value, rate);
            uint256 checkedSupply = safeAdd(totalTokens, tokens);
            require(checkedSupply <= tokenGenerationMax);
    
            totalTokens = checkedSupply;
            contributorTokens = safeAdd(contributorTokens, tokens);
            
            Transfer(address(this), _participant, tokens);
            balances[_participant] = safeAdd(balances[_participant], tokens);
            contribution[_participant] = safeAdd(contribution[_participant], msg.value);
            WolkCreated(_participant, tokens); // logs token creation
        }
    
        function finalize() onlyOwner external {
            require(!allSaleCompleted);
            end_time = block.timestamp;
    
            // 50MM Wolk allocated to Wolk Inc for development
            uint256 wolkincTokens =  50 * 10**6 * 10**decimals;
            balances[wolkInc] = wolkincTokens;
            totalTokens = safeAdd(totalTokens, wolkincTokens);                 
    
            WolkCreated(wolkInc, wolkincTokens); // logs token creation 
            allSaleCompleted = true;
            reserveBalance = safeDiv(safeMul(contributorTokens, percentageETHReserve), 100000);
            var withdrawalBalance = safeSub(this.balance, reserveBalance);
            msg.sender.transfer(withdrawalBalance);
        }
    
        function refund() external {
            require((contribution[msg.sender] > 0) && (!allSaleCompleted) && (block.timestamp > end_time)  && (totalTokens < tokenGenerationMin));
            uint256 tokenBalance = balances[msg.sender];
            uint256 refundBalance = contribution[msg.sender];
            balances[msg.sender] = 0;
            contribution[msg.sender] = 0;
            totalTokens = safeSub(totalTokens, tokenBalance);
            WolkDestroyed(msg.sender, tokenBalance);
            LogRefund(msg.sender, refundBalance);
            msg.sender.transfer(refundBalance); 
        }
    
        function transferAnyERC20Token(address _tokenAddress, uint256 _amount) onlyOwner returns (bool success) {
            return ERC20(_tokenAddress).transfer(owner, _amount);
        }
    }
    
    // Taken from https://github.com/bancorprotocol/contracts/blob/master/solidity/contracts/BancorFormula.sol
    contract IBancorFormula {
        function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint8 _reserveRatio, uint256 _depositAmount) public constant returns (uint256);
        function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint8 _reserveRatio, uint256 _sellAmount) public constant returns (uint256);
    }
    
    contract WolkExchange is  WolkTGE {
        address public exchangeFormula;
        bool    public isPurchasePossible = false;
        bool    public isSellPossible = false;
    
        modifier isPurchasable { require(isPurchasePossible && allSaleCompleted); _; }
        modifier isSellable { require(isSellPossible && allSaleCompleted); _; }
        
        // @param  _newExchangeformula
        // @return success
        // @dev Set the bancor formula to use -- only Wolk Inc can set this
        function setExchangeFormula(address _newExchangeformula) onlyOwner returns (bool success){
            require(sellWolkEstimate(10**decimals, _newExchangeformula) > 0);
            require(purchaseWolkEstimate(10**decimals, _newExchangeformula) > 0);
            isPurchasePossible = false;
            isSellPossible = false;
            exchangeFormula = _newExchangeformula;
            return true;
        }
    
        // @param  _newReserveRatio
        // @return success
        // @dev Set the reserve ratio in case of emergency -- only Wolk Inc can set this
        function updateReserveRatio(uint8 _newReserveRatio) onlyOwner returns (bool success) {
            require(allSaleCompleted && ( _newReserveRatio > 1 ) && ( _newReserveRatio < 20 ) );
            percentageETHReserve = _newReserveRatio;
            return true;
        }
    
        // @param  _isRunning
        // @return success
        // @dev updating isPurchasePossible -- only Wolk Inc can set this
        function updatePurchasePossible(bool _isRunning) onlyOwner returns (bool success){
            if (_isRunning){
                require(sellWolkEstimate(10**decimals, exchangeFormula) > 0);
                require(purchaseWolkEstimate(10**decimals, exchangeFormula) > 0);   
            }
            isPurchasePossible = _isRunning;
            return true;
        }
    
        // @param  _isRunning
        // @return success
        // @dev updating isSellPossible -- only Wolk Inc can set this
        function updateSellPossible(bool _isRunning) onlyOwner returns (bool success){
            if (_isRunning){
                require(sellWolkEstimate(10**decimals, exchangeFormula) > 0);
                require(purchaseWolkEstimate(10**decimals, exchangeFormula) > 0);   
            }
            isSellPossible = _isRunning;
            return true;
        }
    
        function sellWolkEstimate(uint256 _wolkAmountest, address _formula) internal returns(uint256) {
            uint256 ethReceivable =  IBancorFormula(_formula).calculateSaleReturn(contributorTokens, reserveBalance, percentageETHReserve, _wolkAmountest);
            return ethReceivable;
        }
        
        function purchaseWolkEstimate(uint256 _ethAmountest, address _formula) internal returns(uint256) {
            uint256 wolkReceivable = IBancorFormula(_formula).calculatePurchaseReturn(contributorTokens, reserveBalance, percentageETHReserve, _ethAmountest);
            return wolkReceivable;
        }
        
        // @param _wolkAmount
        // @return ethReceivable
        // @dev send Wolk into contract in exchange for eth, at an exchange rate based on the Bancor Protocol derivation and decrease totalSupply accordingly
        function sellWolk(uint256 _wolkAmount) isSellable() returns(uint256) {
            require((balances[msg.sender] >= _wolkAmount));
            uint256 ethReceivable = sellWolkEstimate(_wolkAmount,exchangeFormula);
            require(this.balance > ethReceivable);
            balances[msg.sender] = safeSub(balances[msg.sender], _wolkAmount);
            contributorTokens = safeSub(contributorTokens, _wolkAmount);
            totalTokens = safeSub(totalTokens, _wolkAmount);
            reserveBalance = safeSub(this.balance, ethReceivable);
            WolkDestroyed(msg.sender, _wolkAmount);
            Transfer(msg.sender, 0x00000000000000000000, _wolkAmount);
            msg.sender.transfer(ethReceivable);
            return ethReceivable;     
        }
    
        // @return wolkReceivable    
        // @dev send eth into contract in exchange for Wolk tokens, at an exchange rate based on the Bancor Protocol derivation and increase totalSupply accordingly
        function purchaseWolk(address _buyer) isPurchasable() payable returns(uint256){
            require(msg.value > 0);
            uint256 wolkReceivable = purchaseWolkEstimate(msg.value, exchangeFormula);
            require(wolkReceivable > 0);
    
            contributorTokens = safeAdd(contributorTokens, wolkReceivable);
            totalTokens = safeAdd(totalTokens, wolkReceivable);
            balances[_buyer] = safeAdd(balances[_buyer], wolkReceivable);
            reserveBalance = safeAdd(reserveBalance, msg.value);
            WolkCreated(_buyer, wolkReceivable);
            Transfer(address(this),_buyer,wolkReceivable);
            return wolkReceivable;
        }
    
        // @dev  fallback function for purchase
        // @note Automatically fallback to tokenGenerationEvent before sale is completed. After the token generation event, fallback to purchaseWolk. Liquidity exchange will be enabled through updateExchangeStatus  
        function () payable {
            require(msg.value > 0);
            if(!allSaleCompleted){
                this.tokenGenerationEvent.value(msg.value)(msg.sender);
            } else if ( block.timestamp >= end_time ){
                this.purchaseWolk.value(msg.value)(msg.sender);
            } else {
                revert();
            }
        }
    }