ETH Price: $2,272.99 (-6.32%)

Transaction Decoder

Block:
9236731 at Jan-08-2020 12:24:09 AM +UTC
Transaction Fee:
0.00098796852 ETH $2.25
Gas Used:
784,102 Gas / 1.26 Gwei

Emitted Events:

9 MANAToken.Transfer( from=KyberReserve, to=KyberNetwork, value=2632161218858312399414 )
10 KyberReserve.TradeExecute( origin=KyberNetwork, src=0xEeeeeEee...eeeeeEEeE, srcAmount=608736464484950466, destToken=MANAToken, destAmount=2632161218858312399414, destAddress=KyberNetwork )
11 MANAToken.Transfer( from=KyberNetwork, to=[Receiver] 0x85c5c26dc2af5546341fc1988b9d178148b4838b, value=2632161218858312399414 )
12 FeeBurner.AssignFeeToWallet( reserve=KyberReserve, wallet=0xC9D81352...2ef776D99, walletFee=325790900214944094 )
13 FeeBurner.AssignBurnFees( reserve=KyberReserve, burnFee=760178767168202886 )
14 KyberNetwork.KyberTrade( trader=[Receiver] 0x85c5c26dc2af5546341fc1988b9d178148b4838b, src=0xEeeeeEee...eeeeeEEeE, dest=MANAToken, srcAmount=608736464484950466, dstAmount=2632161218858312399414, destAddress=[Receiver] 0x85c5c26dc2af5546341fc1988b9d178148b4838b, ethWeiValue=608736464484950466, reserve1=0x00000000...000000000, reserve2=KyberReserve, hint=0x )
15 KyberNetworkProxy.ExecuteTrade( trader=[Receiver] 0x85c5c26dc2af5546341fc1988b9d178148b4838b, src=0xEeeeeEee...eeeeeEEeE, dest=MANAToken, actualSrcAmount=608736464484950466, actualDestAmount=2632161218858312399414 )
16 MANAToken.Transfer( from=[Receiver] 0x85c5c26dc2af5546341fc1988b9d178148b4838b, to=BancorNetwork, value=2632158586697093541101 )
17 MANAToken.Approval( owner=BancorNetwork, spender=BancorConverter, value=2632158586697093541101 )
18 MANAToken.Transfer( from=BancorNetwork, to=BancorConverter, value=2632158586697093541101 )
19 SmartToken.Issuance( _amount=103793760251453528146 )
20 SmartToken.Transfer( _from=SmartToken, _to=BancorNetwork, _value=103793760251453528146 )
21 BancorConverter.Conversion( _fromToken=MANAToken, _toToken=SmartToken, _trader=BancorNetwork, _amount=2632158586697093541101, _return=103793760251453528146, _currentPriceN=997518774804301051776434000000, _currentPriceD=39348432222017171675721000000 )
22 SmartToken.Transfer( _from=BancorNetwork, _to=SmartToken, _value=103793760251453528146 )
23 SmartToken.Destruction( _amount=103793760251453528146 )
24 SmartToken.Transfer( _from=BancorConverter, _to=BancorNetwork, _value=385426641792964556887 )
25 BancorConverter.Conversion( _fromToken=SmartToken, _toToken=SmartToken, _trader=BancorNetwork, _amount=103793760251453528146, _return=385426641792964556887, _currentPriceN=39296535341891444911648000000, _currentPriceD=145973400778962223278531000000 )
26 SmartToken.Approval( _owner=BancorNetwork, _spender=BancorConverter, _value=385426641792964556887 )
27 SmartToken.Transfer( _from=BancorNetwork, _to=BancorConverter, _value=385426641792964556887 )
28 EtherToken.Transfer( _from=BancorConverter, _to=BancorNetwork, _value=609978729092234748 )
29 BancorConverter.Conversion( _fromToken=SmartToken, _toToken=EtherToken, _trader=BancorNetwork, _amount=385426641792964556887, _return=609978729092234748, _conversionFee=1221789837340221 )
30 BancorConverter.PriceDataUpdate( _connectorToken=SmartToken, _tokenSupply=13836827578603836371025058, _connectorBalance=7999992199617334151617347, _connectorWeight=500000 )
31 BancorConverter.PriceDataUpdate( _connectorToken=EtherToken, _tokenSupply=13836827578603836371025058, _connectorBalance=12685589815589120810515, _connectorWeight=500000 )
32 EtherToken.Transfer( _from=BancorNetwork, _to=EtherToken, _value=609978729092234748 )
33 EtherToken.Destruction( _amount=609978729092234748 )

Account State Difference:

  Address   Before After State Difference Code
0x0F5D2fB2...8908cC942
0x1F573D6F...d79a7FF1C
0x55aE3f67...d2DA108C5
0.739152801375828175 Eth
Nonce: 126329
0.738164832855828175 Eth
Nonce: 126330
0.00098796852
0x63825c17...bD36A0D8F
(Kyber: Reserve)
2,823.685151405367486881 Eth2,824.293887869852437347 Eth0.608736464484950466
0x65bF64Ff...77ced86Cd
(Kyber: Contract)
0x798AbDA6...d3d11191B
(Kyber: Conversion Rates)
0x8007aa43...E5fF626d1
(Kyber: Fee Burner)
0x85C5c26D...148b4838B 228.332374865889297756 Eth228.333617130496582038 Eth0.001242264607284282
0xc0829421...2db2cE315 12,799.593152536206977838 Eth12,798.98317380711474309 Eth0.609978729092234748
(Ethermine)
778.57014384633652076 Eth778.57113181485652076 Eth0.00098796852

Execution Trace

0x85c5c26dc2af5546341fc1988b9d178148b4838b.ab5898e8( )
  • 0x54f56ba1201188188866cc24d88f31f23d2795d9.b6f9385d( )
    • BancorConverter.getReturn( _fromToken=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, _toToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _amount=2632158586697093541101 ) => ( 385426641792964556887 )
      • SmartToken.CALL( )
      • SmartToken.CALL( )
      • MANAToken.balanceOf( _owner=0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( balance=994886616217603958235333 )
      • BancorConverterExtensions.CALL( )
      • BancorFormula.calculatePurchaseReturn( _supply=78593070683782889823296, _connectorBalance=994886616217603958235333, _connectorWeight=500000, _depositAmount=2632158586697093541101 ) => ( 103897657909362891037 )
      • SmartToken.CALL( )
      • SmartToken.CALL( )
      • SmartToken.balanceOf( 0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( 146358827420755187835418 )
      • BancorConverterExtensions.CALL( )
      • BancorFormula.calculateSaleReturn( _supply=78696864444034343351442, _connectorBalance=146358827420755187835418, _connectorWeight=500000, _sellAmount=103793760251453528146 ) => ( 385812454247211768655 )
      • BancorConverter.getReturn( _fromToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _toToken=0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315, _amount=385426641792964556887 ) => ( 609978729092234748, 1221789837340221 )
        • SmartToken.CALL( )
        • ContractRegistry.addressOf( _contractName=42616E636F72466F726D756C6100000000000000000000000000000000000000 ) => ( 0x524619EB9b4cdFFa7DA13029b33f24635478AFc0 )
        • SmartToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 7999606772975541187060460 )
        • EtherToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 12686199794318213045263 )
        • BancorFormula.calculateCrossReserveReturn( _fromReserveBalance=7999606772975541187060460, _fromReserveRatio=500000, _toReserveBalance=12686199794318213045263, _toReserveRatio=500000, _amount=385426641792964556887 ) => ( 611200518929574969 )
        • 0x54f56ba1201188188866cc24d88f31f23d2795d9.cf0b3890( )
          • ConversionRates.getRate( token=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, currentBlockNumber=9236731, buy=True, qty=608736464484950466 ) => ( 4323974942236085164441 )
          • ETH 0.608736464484950466 KyberNetworkProxy.trade( src=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, srcAmount=608736464484950466, dest=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, destAddress=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B, maxDestAmount=57896044618658097711785492504343953926634992332820282019728792003956564819968, minConversionRate=4323970618261142928353, walletId=0xC9D81352fBdb0294b091e51d774A0652ef776D99 ) => ( 2632161218858312399414 )
            • MANAToken.balanceOf( _owner=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B ) => ( balance=106409268784785877016 )
            • ETH 0.608736464484950466 KyberNetwork.tradeWithHint( trader=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B, src=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, srcAmount=608736464484950466, dest=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, destAddress=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B, maxDestAmount=57896044618658097711785492504343953926634992332820282019728792003956564819968, minConversionRate=4323970618261142928353, walletId=0xC9D81352fBdb0294b091e51d774A0652ef776D99, hint=0x ) => ( 2632161218858312399414 )
              • KyberReserve.getConversionRate( src=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, dest=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, srcQty=608736464484950466, blockNumber=9236731 ) => ( 4323974942236085164441 )
                • ConversionRates.getRate( token=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, currentBlockNumber=9236731, buy=True, qty=608736464484950466 ) => ( 4323974942236085164441 )
                • MANAToken.balanceOf( _owner=0x63825c174ab367968EC60f061753D3bbD36A0D8F ) => ( balance=81052503427239017906783 )
                • SanityRates.getSanityRate( src=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, dest=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942 ) => ( 4667116258089304339955 )
                • ETH 0.608736464484950466 KyberReserve.trade( srcToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, srcAmount=608736464484950466, destToken=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, destAddress=0x65bF64Ff5f51272f729BDcD7AcFB00677ced86Cd, conversionRate=4323974942236085164441, validate=True ) => ( True )
                  • ConversionRates.recordImbalance( token=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, buyAmount=2632161218858312399414, rateUpdateBlock=0, currentBlock=9236731 )
                  • MANAToken.transfer( _to=0x65bF64Ff5f51272f729BDcD7AcFB00677ced86Cd, _value=2632161218858312399414 ) => ( True )
                  • MANAToken.transfer( _to=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B, _value=2632161218858312399414 ) => ( True )
                  • FeeBurner.handleFees( tradeWeiAmount=608736464484950466, reserve=0x63825c174ab367968EC60f061753D3bbD36A0D8F, wallet=0xC9D81352fBdb0294b091e51d774A0652ef776D99 ) => ( True )
                  • MANAToken.balanceOf( _owner=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B ) => ( balance=2738570487643098276430 )
                  • BancorConverter.quickConvert( _path=[0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, 0x79d83B390cF0EDF86B9EFbE47B556Cc6e20926aC, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0xb1CD6e4153B2a390Cf00A6556b0fC1458C4A5533, 0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315], _amount=2632158586697093541101, _minReturn=1 ) => ( 609978729092234748 )
                    • BancorConverterExtensions.CALL( )
                    • MANAToken.transferFrom( _from=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B, _to=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _value=2632158586697093541101 ) => ( True )
                    • BancorNetwork.convertFor( _path=[0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, 0x79d83B390cF0EDF86B9EFbE47B556Cc6e20926aC, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0xb1CD6e4153B2a390Cf00A6556b0fC1458C4A5533, 0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315], _amount=2632158586697093541101, _minReturn=1, _for=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B ) => ( 609978729092234748 )
                      • ContractRegistry.addressOf( _contractName=436F6E7472616374466561747572657300000000000000000000000000000000 ) => ( 0x563172281800B139f69fB038cC2C08CaD56Ce699 )
                      • SmartToken.CALL( )
                      • ContractFeatures.isSupported( _contract=0x967f1c667fC490ddd2fb941e3a461223C03D40e9, _features=1 ) => ( False )
                      • SmartToken.CALL( )
                      • ContractFeatures.isSupported( _contract=0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA, _features=1 ) => ( True )
                      • BancorConverter.CALL( )
                      • ContractRegistry.addressOf( _contractName=42616E636F7247617350726963654C696D697400000000000000000000000000 ) => ( 0x607a5C47978e2Eb6d59C6C6f51bc0bF411f4b85a )
                      • BancorGasPriceLimit.validateGasPrice( _gasPrice=1260000000 )
                      • SmartToken.CALL( )
                      • MANAToken.allowance( _owner=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _spender=0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( remaining=0 )
                      • MANAToken.allowance( _owner=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _spender=0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( remaining=0 )
                      • MANAToken.approve( _spender=0x967f1c667fC490ddd2fb941e3a461223C03D40e9, _value=2632158586697093541101 ) => ( True )
                      • BancorConverter.change( _fromToken=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942, _toToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _amount=2632158586697093541101, _minReturn=1 ) => ( 385426641792964556887 )
                        • BancorConverterExtensions.CALL( )
                        • BancorGasPriceLimit.CALL( )
                        • SmartToken.CALL( )
                        • SmartToken.CALL( )
                        • MANAToken.balanceOf( _owner=0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( balance=994886616217603958235333 )
                        • BancorConverterExtensions.CALL( )
                        • BancorFormula.calculatePurchaseReturn( _supply=78593070683782889823296, _connectorBalance=994886616217603958235333, _connectorWeight=500000, _depositAmount=2632158586697093541101 ) => ( 103897657909362891037 )
                        • MANAToken.transferFrom( _from=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _to=0x967f1c667fC490ddd2fb941e3a461223C03D40e9, _value=2632158586697093541101 ) => ( True )
                        • SmartToken.issue( _to=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _amount=103793760251453528146 )
                        • MANAToken.balanceOf( _owner=0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( balance=997518774804301051776434 )
                        • SmartToken.CALL( )
                        • SmartToken.CALL( )
                        • MANAToken.CALL( )
                        • BancorConverterExtensions.CALL( )
                        • BancorGasPriceLimit.CALL( )
                        • SmartToken.balanceOf( 0x0e936B11c2e7b601055e58c7E32417187aF4de4a ) => ( 103793760251453528146 )
                        • SmartToken.CALL( )
                        • SmartToken.CALL( )
                        • SmartToken.balanceOf( 0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( 146358827420755187835418 )
                        • BancorConverterExtensions.CALL( )
                        • BancorFormula.calculateSaleReturn( _supply=78696864444034343351442, _connectorBalance=146358827420755187835418, _connectorWeight=500000, _sellAmount=103793760251453528146 ) => ( 385812454247211768655 )
                        • SmartToken.CALL( )
                        • SmartToken.balanceOf( 0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( 146358827420755187835418 )
                        • SmartToken.destroy( _from=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _amount=103793760251453528146 )
                        • SmartToken.transfer( _to=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _value=385426641792964556887 ) => ( success=True )
                        • SmartToken.balanceOf( 0x967f1c667fC490ddd2fb941e3a461223C03D40e9 ) => ( 145973400778962223278531 )
                        • SmartToken.CALL( )
                        • SmartToken.CALL( )
                        • SmartToken.CALL( )
                        • SmartToken.CALL( )
                        • SmartToken.allowance( 0x0e936B11c2e7b601055e58c7E32417187aF4de4a, 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 0 )
                        • SmartToken.allowance( 0x0e936B11c2e7b601055e58c7E32417187aF4de4a, 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 0 )
                        • SmartToken.approve( _spender=0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA, _value=385426641792964556887 ) => ( success=True )
                        • BancorConverter.change( _fromToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _toToken=0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315, _amount=385426641792964556887, _minReturn=1 ) => ( 609978729092234748 )
                          • ContractRegistry.addressOf( _contractName=42616E636F724E6574776F726B00000000000000000000000000000000000000 ) => ( 0x0e936B11c2e7b601055e58c7E32417187aF4de4a )
                          • SmartToken.CALL( )
                          • ContractRegistry.addressOf( _contractName=42616E636F72466F726D756C6100000000000000000000000000000000000000 ) => ( 0x524619EB9b4cdFFa7DA13029b33f24635478AFc0 )
                          • SmartToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 7999606772975541187060460 )
                          • EtherToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 12686199794318213045263 )
                          • BancorFormula.calculateCrossReserveReturn( _fromReserveBalance=7999606772975541187060460, _fromReserveRatio=500000, _toReserveBalance=12686199794318213045263, _toReserveRatio=500000, _amount=385426641792964556887 ) => ( 611200518929574969 )
                          • EtherToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 12686199794318213045263 )
                          • SmartToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 7999606772975541187060460 )
                          • SmartToken.transferFrom( _from=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _to=0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA, _value=385426641792964556887 ) => ( success=True )
                          • SmartToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 7999992199617334151617347 )
                          • EtherToken.balanceOf( 0x0e936B11c2e7b601055e58c7E32417187aF4de4a ) => ( 0 )
                          • EtherToken.transfer( _to=0x0e936B11c2e7b601055e58c7E32417187aF4de4a, _value=609978729092234748 ) => ( success=True )
                          • EtherToken.balanceOf( 0x0e936B11c2e7b601055e58c7E32417187aF4de4a ) => ( 609978729092234748 )
                          • SmartToken.CALL( )
                          • SmartToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 7999992199617334151617347 )
                          • SmartToken.CALL( )
                          • EtherToken.balanceOf( 0xd3ec78814966Ca1Eb4c923aF4Da86BF7e6c743bA ) => ( 12685589815589120810515 )
                          • EtherToken.withdrawTo( _to=0x85C5c26DC2aF5546341Fc1988B9d178148b4838B, _amount=609978729092234748 )
                            • ETH 0.609978729092234748 0x85c5c26dc2af5546341fc1988b9d178148b4838b.CALL( )
                              File 1 of 20: KyberReserve
                              pragma solidity 0.4.18;
                              
                              contract Utils {
                              
                                  ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
                                  uint  constant internal PRECISION = (10**18);
                                  uint  constant internal MAX_QTY   = (10**28); // 10B tokens
                                  uint  constant internal MAX_RATE  = (PRECISION * 10**6); // up to 1M tokens per ETH
                                  uint  constant internal MAX_DECIMALS = 18;
                                  uint  constant internal ETH_DECIMALS = 18;
                                  mapping(address=>uint) internal decimals;
                              
                                  function setDecimals(ERC20 token) internal {
                                      if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
                                      else decimals[token] = token.decimals();
                                  }
                              
                                  function getDecimals(ERC20 token) internal view returns(uint) {
                                      if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
                                      uint tokenDecimals = decimals[token];
                                      // technically, there might be token with decimals 0
                                      // moreover, very possible that old tokens have decimals 0
                                      // these tokens will just have higher gas fees.
                                      if(tokenDecimals == 0) return token.decimals();
                              
                                      return tokenDecimals;
                                  }
                              
                                  function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
                                      require(srcQty <= MAX_QTY);
                                      require(rate <= MAX_RATE);
                              
                                      if (dstDecimals >= srcDecimals) {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
                                      } else {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
                                      }
                                  }
                              
                                  function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
                                      require(dstQty <= MAX_QTY);
                                      require(rate <= MAX_RATE);
                              
                                      //source quantity is rounded up. to avoid dest quantity being too low.
                                      uint numerator;
                                      uint denominator;
                                      if (srcDecimals >= dstDecimals) {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
                                          denominator = rate;
                                      } else {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          numerator = (PRECISION * dstQty);
                                          denominator = (rate * (10**(dstDecimals - srcDecimals)));
                                      }
                                      return (numerator + denominator - 1) / denominator; //avoid rounding down errors
                                  }
                              }
                              
                              contract PermissionGroups {
                              
                                  address public admin;
                                  address public pendingAdmin;
                                  mapping(address=>bool) internal operators;
                                  mapping(address=>bool) internal alerters;
                                  address[] internal operatorsGroup;
                                  address[] internal alertersGroup;
                                  uint constant internal MAX_GROUP_SIZE = 50;
                              
                                  function PermissionGroups() public {
                                      admin = msg.sender;
                                  }
                              
                                  modifier onlyAdmin() {
                                      require(msg.sender == admin);
                                      _;
                                  }
                              
                                  modifier onlyOperator() {
                                      require(operators[msg.sender]);
                                      _;
                                  }
                              
                                  modifier onlyAlerter() {
                                      require(alerters[msg.sender]);
                                      _;
                                  }
                              
                                  function getOperators () external view returns(address[]) {
                                      return operatorsGroup;
                                  }
                              
                                  function getAlerters () external view returns(address[]) {
                                      return alertersGroup;
                                  }
                              
                                  event TransferAdminPending(address pendingAdmin);
                              
                                  /**
                                   * @dev Allows the current admin to set the pendingAdmin address.
                                   * @param newAdmin The address to transfer ownership to.
                                   */
                                  function transferAdmin(address newAdmin) public onlyAdmin {
                                      require(newAdmin != address(0));
                                      TransferAdminPending(pendingAdmin);
                                      pendingAdmin = newAdmin;
                                  }
                              
                                  /**
                                   * @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
                                   * @param newAdmin The address to transfer ownership to.
                                   */
                                  function transferAdminQuickly(address newAdmin) public onlyAdmin {
                                      require(newAdmin != address(0));
                                      TransferAdminPending(newAdmin);
                                      AdminClaimed(newAdmin, admin);
                                      admin = newAdmin;
                                  }
                              
                                  event AdminClaimed( address newAdmin, address previousAdmin);
                              
                                  /**
                                   * @dev Allows the pendingAdmin address to finalize the change admin process.
                                   */
                                  function claimAdmin() public {
                                      require(pendingAdmin == msg.sender);
                                      AdminClaimed(pendingAdmin, admin);
                                      admin = pendingAdmin;
                                      pendingAdmin = address(0);
                                  }
                              
                                  event AlerterAdded (address newAlerter, bool isAdd);
                              
                                  function addAlerter(address newAlerter) public onlyAdmin {
                                      require(!alerters[newAlerter]); // prevent duplicates.
                                      require(alertersGroup.length < MAX_GROUP_SIZE);
                              
                                      AlerterAdded(newAlerter, true);
                                      alerters[newAlerter] = true;
                                      alertersGroup.push(newAlerter);
                                  }
                              
                                  function removeAlerter (address alerter) public onlyAdmin {
                                      require(alerters[alerter]);
                                      alerters[alerter] = false;
                              
                                      for (uint i = 0; i < alertersGroup.length; ++i) {
                                          if (alertersGroup[i] == alerter) {
                                              alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
                                              alertersGroup.length--;
                                              AlerterAdded(alerter, false);
                                              break;
                                          }
                                      }
                                  }
                              
                                  event OperatorAdded(address newOperator, bool isAdd);
                              
                                  function addOperator(address newOperator) public onlyAdmin {
                                      require(!operators[newOperator]); // prevent duplicates.
                                      require(operatorsGroup.length < MAX_GROUP_SIZE);
                              
                                      OperatorAdded(newOperator, true);
                                      operators[newOperator] = true;
                                      operatorsGroup.push(newOperator);
                                  }
                              
                                  function removeOperator (address operator) public onlyAdmin {
                                      require(operators[operator]);
                                      operators[operator] = false;
                              
                                      for (uint i = 0; i < operatorsGroup.length; ++i) {
                                          if (operatorsGroup[i] == operator) {
                                              operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
                                              operatorsGroup.length -= 1;
                                              OperatorAdded(operator, false);
                                              break;
                                          }
                                      }
                                  }
                              }
                              
                              interface ConversionRatesInterface {
                              
                                  function recordImbalance(
                                      ERC20 token,
                                      int buyAmount,
                                      uint rateUpdateBlock,
                                      uint currentBlock
                                  )
                                      public;
                              
                                  function getRate(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint);
                              }
                              
                              interface ERC20 {
                                  function totalSupply() public view returns (uint supply);
                                  function balanceOf(address _owner) public view returns (uint balance);
                                  function transfer(address _to, uint _value) public returns (bool success);
                                  function transferFrom(address _from, address _to, uint _value) public returns (bool success);
                                  function approve(address _spender, uint _value) public returns (bool success);
                                  function allowance(address _owner, address _spender) public view returns (uint remaining);
                                  function decimals() public view returns(uint digits);
                                  event Approval(address indexed _owner, address indexed _spender, uint _value);
                              }
                              
                              interface KyberReserveInterface {
                              
                                  function trade(
                                      ERC20 srcToken,
                                      uint srcAmount,
                                      ERC20 destToken,
                                      address destAddress,
                                      uint conversionRate,
                                      bool validate
                                  )
                                      public
                                      payable
                                      returns(bool);
                              
                                  function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint);
                              }
                              
                              interface SanityRatesInterface {
                                  function getSanityRate(ERC20 src, ERC20 dest) public view returns(uint);
                              }
                              
                              contract Withdrawable is PermissionGroups {
                              
                                  event TokenWithdraw(ERC20 token, uint amount, address sendTo);
                              
                                  /**
                                   * @dev Withdraw all ERC20 compatible tokens
                                   * @param token ERC20 The address of the token contract
                                   */
                                  function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
                                      require(token.transfer(sendTo, amount));
                                      TokenWithdraw(token, amount, sendTo);
                                  }
                              
                                  event EtherWithdraw(uint amount, address sendTo);
                              
                                  /**
                                   * @dev Withdraw Ethers
                                   */
                                  function withdrawEther(uint amount, address sendTo) external onlyAdmin {
                                      sendTo.transfer(amount);
                                      EtherWithdraw(amount, sendTo);
                                  }
                              }
                              
                              contract KyberReserve is KyberReserveInterface, Withdrawable, Utils {
                              
                                  address public kyberNetwork;
                                  bool public tradeEnabled;
                                  ConversionRatesInterface public conversionRatesContract;
                                  SanityRatesInterface public sanityRatesContract;
                                  mapping(bytes32=>bool) public approvedWithdrawAddresses; // sha3(token,address)=>bool
                              
                                  function KyberReserve(address _kyberNetwork, ConversionRatesInterface _ratesContract, address _admin) public {
                                      require(_admin != address(0));
                                      require(_ratesContract != address(0));
                                      require(_kyberNetwork != address(0));
                                      kyberNetwork = _kyberNetwork;
                                      conversionRatesContract = _ratesContract;
                                      admin = _admin;
                                      tradeEnabled = true;
                                  }
                              
                                  event DepositToken(ERC20 token, uint amount);
                              
                                  function() public payable {
                                      DepositToken(ETH_TOKEN_ADDRESS, msg.value);
                                  }
                              
                                  event TradeExecute(
                                      address indexed origin,
                                      address src,
                                      uint srcAmount,
                                      address destToken,
                                      uint destAmount,
                                      address destAddress
                                  );
                              
                                  function trade(
                                      ERC20 srcToken,
                                      uint srcAmount,
                                      ERC20 destToken,
                                      address destAddress,
                                      uint conversionRate,
                                      bool validate
                                  )
                                      public
                                      payable
                                      returns(bool)
                                  {
                                      require(tradeEnabled);
                                      require(msg.sender == kyberNetwork);
                              
                                      require(doTrade(srcToken, srcAmount, destToken, destAddress, conversionRate, validate));
                              
                                      return true;
                                  }
                              
                                  event TradeEnabled(bool enable);
                              
                                  function enableTrade() public onlyAdmin returns(bool) {
                                      tradeEnabled = true;
                                      TradeEnabled(true);
                              
                                      return true;
                                  }
                              
                                  function disableTrade() public onlyAlerter returns(bool) {
                                      tradeEnabled = false;
                                      TradeEnabled(false);
                              
                                      return true;
                                  }
                              
                                  event WithdrawAddressApproved(ERC20 token, address addr, bool approve);
                              
                                  function approveWithdrawAddress(ERC20 token, address addr, bool approve) public onlyAdmin {
                                      approvedWithdrawAddresses[keccak256(token, addr)] = approve;
                                      WithdrawAddressApproved(token, addr, approve);
                              
                                      setDecimals(token);
                                  }
                              
                                  event WithdrawFunds(ERC20 token, uint amount, address destination);
                              
                                  function withdraw(ERC20 token, uint amount, address destination) public onlyOperator returns(bool) {
                                      require(approvedWithdrawAddresses[keccak256(token, destination)]);
                              
                                      if (token == ETH_TOKEN_ADDRESS) {
                                          destination.transfer(amount);
                                      } else {
                                          require(token.transfer(destination, amount));
                                      }
                              
                                      WithdrawFunds(token, amount, destination);
                              
                                      return true;
                                  }
                              
                                  event SetContractAddresses(address network, address rate, address sanity);
                              
                                  function setContracts(address _kyberNetwork, ConversionRatesInterface _conversionRates, SanityRatesInterface _sanityRates)
                                      public
                                      onlyAdmin
                                  {
                                      require(_kyberNetwork != address(0));
                                      require(_conversionRates != address(0));
                              
                                      kyberNetwork = _kyberNetwork;
                                      conversionRatesContract = _conversionRates;
                                      sanityRatesContract = _sanityRates;
                              
                                      SetContractAddresses(kyberNetwork, conversionRatesContract, sanityRatesContract);
                                  }
                              
                                  ////////////////////////////////////////////////////////////////////////////
                                  /// status functions ///////////////////////////////////////////////////////
                                  ////////////////////////////////////////////////////////////////////////////
                                  function getBalance(ERC20 token) public view returns(uint) {
                                      if (token == ETH_TOKEN_ADDRESS)
                                          return this.balance;
                                      else
                                          return token.balanceOf(this);
                                  }
                              
                                  function getDestQty(ERC20 src, ERC20 dest, uint srcQty, uint rate) public view returns(uint) {
                                      uint dstDecimals = getDecimals(dest);
                                      uint srcDecimals = getDecimals(src);
                              
                                      return calcDstQty(srcQty, srcDecimals, dstDecimals, rate);
                                  }
                              
                                  function getSrcQty(ERC20 src, ERC20 dest, uint dstQty, uint rate) public view returns(uint) {
                                      uint dstDecimals = getDecimals(dest);
                                      uint srcDecimals = getDecimals(src);
                              
                                      return calcSrcQty(dstQty, srcDecimals, dstDecimals, rate);
                                  }
                              
                                  function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint) {
                                      ERC20 token;
                                      bool  buy;
                              
                                      if (!tradeEnabled) return 0;
                              
                                      if (ETH_TOKEN_ADDRESS == src) {
                                          buy = true;
                                          token = dest;
                                      } else if (ETH_TOKEN_ADDRESS == dest) {
                                          buy = false;
                                          token = src;
                                      } else {
                                          return 0; // pair is not listed
                                      }
                              
                                      uint rate = conversionRatesContract.getRate(token, blockNumber, buy, srcQty);
                                      uint destQty = getDestQty(src, dest, srcQty, rate);
                              
                                      if (getBalance(dest) < destQty) return 0;
                              
                                      if (sanityRatesContract != address(0)) {
                                          uint sanityRate = sanityRatesContract.getSanityRate(src, dest);
                                          if (rate > sanityRate) return 0;
                                      }
                              
                                      return rate;
                                  }
                              
                                  /// @dev do a trade
                                  /// @param srcToken Src token
                                  /// @param srcAmount Amount of src token
                                  /// @param destToken Destination token
                                  /// @param destAddress Destination address to send tokens to
                                  /// @param validate If true, additional validations are applicable
                                  /// @return true iff trade is successful
                                  function doTrade(
                                      ERC20 srcToken,
                                      uint srcAmount,
                                      ERC20 destToken,
                                      address destAddress,
                                      uint conversionRate,
                                      bool validate
                                  )
                                      internal
                                      returns(bool)
                                  {
                                      // can skip validation if done at kyber network level
                                      if (validate) {
                                          require(conversionRate > 0);
                                          if (srcToken == ETH_TOKEN_ADDRESS)
                                              require(msg.value == srcAmount);
                                          else
                                              require(msg.value == 0);
                                      }
                              
                                      uint destAmount = getDestQty(srcToken, destToken, srcAmount, conversionRate);
                                      // sanity check
                                      require(destAmount > 0);
                              
                                      // add to imbalance
                                      ERC20 token;
                                      int buy;
                                      if (srcToken == ETH_TOKEN_ADDRESS) {
                                          buy = int(destAmount);
                                          token = destToken;
                                      } else {
                                          buy = -1 * int(srcAmount);
                                          token = srcToken;
                                      }
                              
                                      conversionRatesContract.recordImbalance(
                                          token,
                                          buy,
                                          0,
                                          block.number
                                      );
                              
                                      // collect src tokens
                                      if (srcToken != ETH_TOKEN_ADDRESS) {
                                          require(srcToken.transferFrom(msg.sender, this, srcAmount));
                                      }
                              
                                      // send dest tokens
                                      if (destToken == ETH_TOKEN_ADDRESS) {
                                          destAddress.transfer(destAmount);
                                      } else {
                                          require(destToken.transfer(destAddress, destAmount));
                                      }
                              
                                      TradeExecute(msg.sender, srcToken, srcAmount, destToken, destAmount, destAddress);
                              
                                      return true;
                                  }
                              }

                              File 2 of 20: KyberNetwork
                              {"ERC20Interface.sol":{"content":"pragma solidity 0.4.18;\n\n\n// https://github.com/ethereum/EIPs/issues/20\ninterface ERC20 {\n    function totalSupply() public view returns (uint supply);\n    function balanceOf(address _owner) public view returns (uint balance);\n    function transfer(address _to, uint _value) public returns (bool success);\n    function transferFrom(address _from, address _to, uint _value) public returns (bool success);\n    function approve(address _spender, uint _value) public returns (bool success);\n    function allowance(address _owner, address _spender) public view returns (uint remaining);\n    function decimals() public view returns(uint digits);\n    event Approval(address indexed _owner, address indexed _spender, uint _value);\n}\n"},"ExpectedRateInterface.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\n\n\ninterface ExpectedRateInterface {\n    function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty, bool usePermissionless) public view\n        returns (uint expectedRate, uint slippageRate);\n}\n"},"FeeBurnerInterface.sol":{"content":"pragma solidity 0.4.18;\n\n\ninterface FeeBurnerInterface {\n    function handleFees (uint tradeWeiAmount, address reserve, address wallet) public returns(bool);\n    function setReserveData(address reserve, uint feesInBps, address kncWallet) public;\n}\n"},"KyberNetwork.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\nimport \"./KyberReserveInterface.sol\";\nimport \"./KyberNetworkInterface.sol\";\nimport \"./Withdrawable.sol\";\nimport \"./Utils3.sol\";\nimport \"./WhiteListInterface.sol\";\nimport \"./ExpectedRateInterface.sol\";\nimport \"./FeeBurnerInterface.sol\";\n\n\n/**\n * @title Helps contracts guard against reentrancy attacks.\n */\ncontract ReentrancyGuard {\n\n    /// @dev counter to allow mutex lock with only one SSTORE operation\n    uint256 private guardCounter = 1;\n\n    /**\n     * @dev Prevents a function from calling itself, directly or indirectly.\n     * Calling one `nonReentrant` function from\n     * another is not supported. Instead, you can implement a\n     * `private` function doing the actual work, and an `external`\n     * wrapper marked as `nonReentrant`.\n     */\n    modifier nonReentrant() {\n        guardCounter += 1;\n        uint256 localCounter = guardCounter;\n        _;\n        require(localCounter == guardCounter);\n    }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////\n/// @title Kyber Network main contract\ncontract KyberNetwork is Withdrawable, Utils3, KyberNetworkInterface, ReentrancyGuard {\n\n    bytes public constant PERM_HINT = \"PERM\";\n    uint  public constant PERM_HINT_GET_RATE = 1 \u003c\u003c 255; // for get rate. bit mask hint.\n\n    uint public negligibleRateDiff = 10; // basic rate steps will be in 0.01%\n    KyberReserveInterface[] public reserves;\n    mapping(address=\u003eReserveType) public reserveType;\n    WhiteListInterface public whiteListContract;\n    ExpectedRateInterface public expectedRateContract;\n    FeeBurnerInterface    public feeBurnerContract;\n    address               public kyberNetworkProxyContract;\n    uint                  public maxGasPriceValue = 50 * 1000 * 1000 * 1000; // 50 gwei\n    bool                  public isEnabled = false; // network is enabled\n    mapping(bytes32=\u003euint) public infoFields; // this is only a UI field for external app.\n\n    mapping(address=\u003eaddress[]) public reservesPerTokenSrc; //reserves supporting token to eth\n    mapping(address=\u003eaddress[]) public reservesPerTokenDest;//reserves support eth to token\n\n    enum ReserveType {NONE, PERMISSIONED, PERMISSIONLESS}\n    bytes internal constant EMPTY_HINT = \"\";\n\n    function KyberNetwork(address _admin) public {\n        require(_admin != address(0));\n        admin = _admin;\n    }\n\n    event EtherReceival(address indexed sender, uint amount);\n\n    /* solhint-disable no-complex-fallback */\n    function() public payable {\n        EtherReceival(msg.sender, msg.value);\n    }\n    /* solhint-enable no-complex-fallback */\n\n    struct TradeInput {\n        address trader;\n        ERC20 src;\n        uint srcAmount;\n        ERC20 dest;\n        address destAddress;\n        uint maxDestAmount;\n        uint minConversionRate;\n        address walletId;\n        bytes hint;\n    }\n\n    function tradeWithHint(\n        address trader,\n        ERC20 src,\n        uint srcAmount,\n        ERC20 dest,\n        address destAddress,\n        uint maxDestAmount,\n        uint minConversionRate,\n        address walletId,\n        bytes hint\n    )\n        public\n        nonReentrant\n        payable\n        returns(uint)\n    {\n        require(msg.sender == kyberNetworkProxyContract);\n        require((hint.length == 0) || (hint.length == 4));\n\n        TradeInput memory tradeInput;\n\n        tradeInput.trader = trader;\n        tradeInput.src = src;\n        tradeInput.srcAmount = srcAmount;\n        tradeInput.dest = dest;\n        tradeInput.destAddress = destAddress;\n        tradeInput.maxDestAmount = maxDestAmount;\n        tradeInput.minConversionRate = minConversionRate;\n        tradeInput.walletId = walletId;\n        tradeInput.hint = hint;\n\n        return trade(tradeInput);\n    }\n\n    event AddReserveToNetwork(KyberReserveInterface indexed reserve, bool add, bool isPermissionless);\n\n    /// @notice can be called only by operator\n    /// @dev add or deletes a reserve to/from the network.\n    /// @param reserve The reserve address.\n    /// @param isPermissionless is the new reserve from permissionless type.\n    function addReserve(KyberReserveInterface reserve, bool isPermissionless) public onlyOperator\n        returns(bool)\n    {\n        require(reserveType[reserve] == ReserveType.NONE);\n        reserves.push(reserve);\n\n        reserveType[reserve] = isPermissionless ? ReserveType.PERMISSIONLESS : ReserveType.PERMISSIONED;\n\n        AddReserveToNetwork(reserve, true, isPermissionless);\n\n        return true;\n    }\n\n    event RemoveReserveFromNetwork(KyberReserveInterface reserve);\n\n    /// @notice can be called only by operator\n    /// @dev removes a reserve from Kyber network.\n    /// @param reserve The reserve address.\n    /// @param index in reserve array.\n    function removeReserve(KyberReserveInterface reserve, uint index) public onlyOperator\n        returns(bool)\n    {\n\n        require(reserveType[reserve] != ReserveType.NONE);\n        require(reserves[index] == reserve);\n\n        reserveType[reserve] = ReserveType.NONE;\n        reserves[index] = reserves[reserves.length - 1];\n        reserves.length--;\n\n        RemoveReserveFromNetwork(reserve);\n\n        return true;\n    }\n\n    event ListReservePairs(address indexed reserve, ERC20 src, ERC20 dest, bool add);\n\n    /// @notice can be called only by operator\n    /// @dev allow or prevent a specific reserve to trade a pair of tokens\n    /// @param reserve The reserve address.\n    /// @param token token address\n    /// @param ethToToken will it support ether to token trade\n    /// @param tokenToEth will it support token to ether trade\n    /// @param add If true then list this pair, otherwise unlist it.\n    function listPairForReserve(address reserve, ERC20 token, bool ethToToken, bool tokenToEth, bool add)\n        public\n        onlyOperator\n        returns(bool)\n    {\n        require(reserveType[reserve] != ReserveType.NONE);\n\n        if (ethToToken) {\n            listPairs(reserve, token, false, add);\n\n            ListReservePairs(reserve, ETH_TOKEN_ADDRESS, token, add);\n        }\n\n        if (tokenToEth) {\n            listPairs(reserve, token, true, add);\n\n            if (add) {\n                require(token.approve(reserve, 2**255)); // approve infinity\n            } else {\n                require(token.approve(reserve, 0));\n            }\n\n            ListReservePairs(reserve, token, ETH_TOKEN_ADDRESS, add);\n        }\n\n        setDecimals(token);\n\n        return true;\n    }\n\n    event WhiteListContractSet(WhiteListInterface newContract, WhiteListInterface currentContract);\n\n    ///@param whiteList can be empty\n    function setWhiteList(WhiteListInterface whiteList) public onlyAdmin {\n        WhiteListContractSet(whiteList, whiteListContract);\n        whiteListContract = whiteList;\n    }\n\n    event ExpectedRateContractSet(ExpectedRateInterface newContract, ExpectedRateInterface currentContract);\n\n    function setExpectedRate(ExpectedRateInterface expectedRate) public onlyAdmin {\n        require(expectedRate != address(0));\n\n        ExpectedRateContractSet(expectedRate, expectedRateContract);\n        expectedRateContract = expectedRate;\n    }\n\n    event FeeBurnerContractSet(FeeBurnerInterface newContract, FeeBurnerInterface currentContract);\n\n    function setFeeBurner(FeeBurnerInterface feeBurner) public onlyAdmin {\n        require(feeBurner != address(0));\n\n        FeeBurnerContractSet(feeBurner, feeBurnerContract);\n        feeBurnerContract = feeBurner;\n    }\n\n    event KyberNetwrokParamsSet(uint maxGasPrice, uint negligibleRateDiff);\n\n    function setParams(\n        uint                  _maxGasPrice,\n        uint                  _negligibleRateDiff\n    )\n        public\n        onlyAdmin\n    {\n        require(_negligibleRateDiff \u003c= 100 * 100); // at most 100%\n\n        maxGasPriceValue = _maxGasPrice;\n        negligibleRateDiff = _negligibleRateDiff;\n        KyberNetwrokParamsSet(maxGasPriceValue, negligibleRateDiff);\n    }\n\n    event KyberNetworkSetEnable(bool isEnabled);\n\n    function setEnable(bool _enable) public onlyAdmin {\n        if (_enable) {\n            require(feeBurnerContract != address(0));\n            require(expectedRateContract != address(0));\n            require(kyberNetworkProxyContract != address(0));\n        }\n        isEnabled = _enable;\n\n        KyberNetworkSetEnable(isEnabled);\n    }\n\n    function setInfo(bytes32 field, uint value) public onlyOperator {\n        infoFields[field] = value;\n    }\n\n    event KyberProxySet(address proxy, address sender);\n\n    function setKyberProxy(address networkProxy) public onlyAdmin {\n        require(networkProxy != address(0));\n        kyberNetworkProxyContract = networkProxy;\n        KyberProxySet(kyberNetworkProxyContract, msg.sender);\n    }\n\n    /// @dev returns number of reserves\n    /// @return number of reserves\n    function getNumReserves() public view returns(uint) {\n        return reserves.length;\n    }\n\n    /// @notice should be called off chain\n    /// @dev get an array of all reserves\n    /// @return An array of all reserves\n    function getReserves() public view returns(KyberReserveInterface[]) {\n        return reserves;\n    }\n\n    function maxGasPrice() public view returns(uint) {\n        return maxGasPriceValue;\n    }\n\n    function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty)\n        public view\n        returns(uint expectedRate, uint slippageRate)\n    {\n        require(expectedRateContract != address(0));\n        if (src == dest) return (0,0);\n        bool includePermissionless = true;\n\n        if (srcQty \u0026 PERM_HINT_GET_RATE \u003e 0) {\n            includePermissionless = false;\n            srcQty = srcQty \u0026 ~PERM_HINT_GET_RATE;\n        }\n\n        return expectedRateContract.getExpectedRate(src, dest, srcQty, includePermissionless);\n    }\n\n    function getExpectedRateOnlyPermission(ERC20 src, ERC20 dest, uint srcQty)\n        public view\n        returns(uint expectedRate, uint slippageRate)\n    {\n        require(expectedRateContract != address(0));\n        if (src == dest) return (0,0);\n        return expectedRateContract.getExpectedRate(src, dest, srcQty, false);\n    }\n\n    function getUserCapInWei(address user) public view returns(uint) {\n        if (whiteListContract == address(0)) return (2 ** 255);\n        return whiteListContract.getUserCapInWei(user);\n    }\n\n    function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint) {\n        //future feature\n        user;\n        token;\n        require(false);\n    }\n\n    struct BestRateResult {\n        uint rate;\n        address reserve1;\n        address reserve2;\n        uint weiAmount;\n        uint rateSrcToEth;\n        uint rateEthToDest;\n        uint destAmount;\n    }\n\n    /// @notice use token address ETH_TOKEN_ADDRESS for ether\n    /// @dev best conversion rate for a pair of tokens, if number of reserves have small differences. randomize\n    /// @param src Src token\n    /// @param dest Destination token\n    /// @return obsolete - used to return best reserve index. not relevant anymore for this API.\n    function findBestRate(ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint obsolete, uint rate) {\n        BestRateResult memory result = findBestRateTokenToToken(src, dest, srcAmount, EMPTY_HINT);\n        return(0, result.rate);\n    }\n\n    function findBestRateOnlyPermission(ERC20 src, ERC20 dest, uint srcAmount)\n        public\n        view\n        returns(uint obsolete, uint rate)\n    {\n        BestRateResult memory result = findBestRateTokenToToken(src, dest, srcAmount, PERM_HINT);\n        return(0, result.rate);\n    }\n\n    function enabled() public view returns(bool) {\n        return isEnabled;\n    }\n\n    function info(bytes32 field) public view returns(uint) {\n        return infoFields[field];\n    }\n\n    /* solhint-disable code-complexity */\n    // Regarding complexity. Below code follows the required algorithm for choosing a reserve.\n    //  It has been tested, reviewed and found to be clear enough.\n    //@dev this function always src or dest are ether. can\u0027t do token to token\n    function searchBestRate(ERC20 src, ERC20 dest, uint srcAmount, bool usePermissionless)\n        public\n        view\n        returns(address, uint)\n    {\n        uint bestRate = 0;\n        uint bestReserve = 0;\n        uint numRelevantReserves = 0;\n\n        //return 1 for ether to ether\n        if (src == dest) return (reserves[bestReserve], PRECISION);\n\n        address[] memory reserveArr;\n\n        reserveArr = src == ETH_TOKEN_ADDRESS ? reservesPerTokenDest[dest] : reservesPerTokenSrc[src];\n\n        if (reserveArr.length == 0) return (reserves[bestReserve], bestRate);\n\n        uint[] memory rates = new uint[](reserveArr.length);\n        uint[] memory reserveCandidates = new uint[](reserveArr.length);\n\n        for (uint i = 0; i \u003c reserveArr.length; i++) {\n            //list all reserves that have this token.\n            if (!usePermissionless \u0026\u0026 reserveType[reserveArr[i]] == ReserveType.PERMISSIONLESS) {\n                continue;\n            }\n\n            rates[i] = (KyberReserveInterface(reserveArr[i])).getConversionRate(src, dest, srcAmount, block.number);\n\n            if (rates[i] \u003e bestRate) {\n                //best rate is highest rate\n                bestRate = rates[i];\n            }\n        }\n\n        if (bestRate \u003e 0) {\n            uint smallestRelevantRate = (bestRate * 10000) / (10000 + negligibleRateDiff);\n\n            for (i = 0; i \u003c reserveArr.length; i++) {\n                if (rates[i] \u003e= smallestRelevantRate) {\n                    reserveCandidates[numRelevantReserves++] = i;\n                }\n            }\n\n            if (numRelevantReserves \u003e 1) {\n                //when encountering small rate diff from bestRate. draw from relevant reserves\n                bestReserve = reserveCandidates[uint(block.blockhash(block.number-1)) % numRelevantReserves];\n            } else {\n                bestReserve = reserveCandidates[0];\n            }\n\n            bestRate = rates[bestReserve];\n        }\n\n        return (reserveArr[bestReserve], bestRate);\n    }\n    /* solhint-enable code-complexity */\n\n    function getReservesRates(ERC20 token, uint optionalAmount) public view\n        returns(address[] buyReserves, uint[] buyRates, address[] sellReserves, uint[] sellRates)\n    {\n        uint amount = optionalAmount \u003e 0 ? optionalAmount : 1000;\n        ERC20 ETH = ETH_TOKEN_ADDRESS;\n\n        buyReserves = reservesPerTokenDest[token];\n        buyRates = new uint[](buyReserves.length);\n\n        for (uint i = 0; i \u003c buyReserves.length; i++) {\n            buyRates[i] = (KyberReserveInterface(buyReserves[i])).getConversionRate(ETH, token, amount, block.number);\n        }\n\n        sellReserves = reservesPerTokenSrc[token];\n        sellRates = new uint[](sellReserves.length);\n\n        for (i = 0; i \u003c sellReserves.length; i++) {\n            sellRates[i] = (KyberReserveInterface(sellReserves[i])).getConversionRate(token, ETH, amount, block.number);\n        }\n    }\n\n    function findBestRateTokenToToken(ERC20 src, ERC20 dest, uint srcAmount, bytes hint) internal view\n        returns(BestRateResult result)\n    {\n        //by default we use permission less reserves\n        bool usePermissionless = true;\n\n        // if hint in first 4 bytes == \u0027PERM\u0027 only permissioned reserves will be used.\n        if ((hint.length \u003e= 4) \u0026\u0026 (keccak256(hint[0], hint[1], hint[2], hint[3]) == keccak256(PERM_HINT))) {\n            usePermissionless = false;\n        }\n\n        uint srcDecimals = getDecimals(src);\n        uint destDecimals = getDecimals(dest);\n\n        (result.reserve1, result.rateSrcToEth) =\n            searchBestRate(src, ETH_TOKEN_ADDRESS, srcAmount, usePermissionless);\n\n        result.weiAmount = calcDestAmountWithDecimals(srcDecimals, ETH_DECIMALS, srcAmount, result.rateSrcToEth);\n        //if weiAmount is zero, return zero rate to avoid revert in ETH -\u003e token call\n        if (result.weiAmount == 0) {\n            result.rate = 0;\n            return;\n        }\n        \n        (result.reserve2, result.rateEthToDest) =\n            searchBestRate(ETH_TOKEN_ADDRESS, dest, result.weiAmount, usePermissionless);\n\n        result.destAmount = calcDestAmountWithDecimals(ETH_DECIMALS, destDecimals, result.weiAmount, result.rateEthToDest);\n\n        result.rate = calcRateFromQty(srcAmount, result.destAmount, srcDecimals, destDecimals);\n    }\n\n    function listPairs(address reserve, ERC20 token, bool isTokenToEth, bool add) internal {\n        uint i;\n        address[] storage reserveArr = reservesPerTokenDest[token];\n\n        if (isTokenToEth) {\n            reserveArr = reservesPerTokenSrc[token];\n        }\n\n        for (i = 0; i \u003c reserveArr.length; i++) {\n            if (reserve == reserveArr[i]) {\n                if (add) {\n                    break; //already added\n                } else {\n                    //remove\n                    reserveArr[i] = reserveArr[reserveArr.length - 1];\n                    reserveArr.length--;\n                    break;\n                }\n            }\n        }\n\n        if (add \u0026\u0026 i == reserveArr.length) {\n            //if reserve wasn\u0027t found add it\n            reserveArr.push(reserve);\n        }\n    }\n\n    event KyberTrade(address indexed trader, ERC20 src, ERC20 dest, uint srcAmount, uint dstAmount,\n        address destAddress, uint ethWeiValue, address reserve1, address reserve2, bytes hint);\n\n    /* solhint-disable function-max-lines */\n    //  Most of the lines here are functions calls spread over multiple lines. We find this function readable enough\n    /// @notice use token address ETH_TOKEN_ADDRESS for ether\n    /// @dev trade api for kyber network.\n    /// @param tradeInput structure of trade inputs\n    function trade(TradeInput tradeInput) internal returns(uint) {\n        require(isEnabled);\n        require(tx.gasprice \u003c= maxGasPriceValue);\n        require(validateTradeInput(tradeInput.src, tradeInput.srcAmount, tradeInput.dest, tradeInput.destAddress));\n\n        BestRateResult memory rateResult =\n            findBestRateTokenToToken(tradeInput.src, tradeInput.dest, tradeInput.srcAmount, tradeInput.hint);\n\n        require(rateResult.rate \u003e 0);\n        require(rateResult.rate \u003c MAX_RATE);\n        require(rateResult.rate \u003e= tradeInput.minConversionRate);\n\n        uint actualDestAmount;\n        uint weiAmount;\n        uint actualSrcAmount;\n\n        (actualSrcAmount, weiAmount, actualDestAmount) = calcActualAmounts(tradeInput.src,\n            tradeInput.dest,\n            tradeInput.srcAmount,\n            tradeInput.maxDestAmount,\n            rateResult);\n\n        require(getUserCapInWei(tradeInput.trader) \u003e= weiAmount);\n        require(handleChange(tradeInput.src, tradeInput.srcAmount, actualSrcAmount, tradeInput.trader));\n\n        require(doReserveTrade(     //src to ETH\n                tradeInput.src,\n                actualSrcAmount,\n                ETH_TOKEN_ADDRESS,\n                this,\n                weiAmount,\n                KyberReserveInterface(rateResult.reserve1),\n                rateResult.rateSrcToEth,\n                true));\n\n        require(doReserveTrade(     //Eth to dest\n                ETH_TOKEN_ADDRESS,\n                weiAmount,\n                tradeInput.dest,\n                tradeInput.destAddress,\n                actualDestAmount,\n                KyberReserveInterface(rateResult.reserve2),\n                rateResult.rateEthToDest,\n                true));\n\n        if (tradeInput.src != ETH_TOKEN_ADDRESS) //\"fake\" trade. (ether to ether) - don\u0027t burn.\n            require(feeBurnerContract.handleFees(weiAmount, rateResult.reserve1, tradeInput.walletId));\n        if (tradeInput.dest != ETH_TOKEN_ADDRESS) //\"fake\" trade. (ether to ether) - don\u0027t burn.\n            require(feeBurnerContract.handleFees(weiAmount, rateResult.reserve2, tradeInput.walletId));\n\n        KyberTrade({\n            trader: tradeInput.trader,\n            src: tradeInput.src,\n            dest: tradeInput.dest,\n            srcAmount: actualSrcAmount,\n            dstAmount: actualDestAmount,\n            destAddress: tradeInput.destAddress,\n            ethWeiValue: weiAmount,\n            reserve1: (tradeInput.src == ETH_TOKEN_ADDRESS) ? address(0) : rateResult.reserve1,\n            reserve2:  (tradeInput.dest == ETH_TOKEN_ADDRESS) ? address(0) : rateResult.reserve2,\n            hint: tradeInput.hint\n        });\n\n        return actualDestAmount;\n    }\n    /* solhint-enable function-max-lines */\n\n    function calcActualAmounts (ERC20 src, ERC20 dest, uint srcAmount, uint maxDestAmount, BestRateResult rateResult)\n        internal view returns(uint actualSrcAmount, uint weiAmount, uint actualDestAmount)\n    {\n        if (rateResult.destAmount \u003e maxDestAmount) {\n            actualDestAmount = maxDestAmount;\n            weiAmount = calcSrcAmount(ETH_TOKEN_ADDRESS, dest, actualDestAmount, rateResult.rateEthToDest);\n            actualSrcAmount = calcSrcAmount(src, ETH_TOKEN_ADDRESS, weiAmount, rateResult.rateSrcToEth);\n            require(actualSrcAmount \u003c= srcAmount);\n        } else {\n            actualDestAmount = rateResult.destAmount;\n            actualSrcAmount = srcAmount;\n            weiAmount = rateResult.weiAmount;\n        }\n    }\n\n    /// @notice use token address ETH_TOKEN_ADDRESS for ether\n    /// @dev do one trade with a reserve\n    /// @param src Src token\n    /// @param amount amount of src tokens\n    /// @param dest   Destination token\n    /// @param destAddress Address to send tokens to\n    /// @param reserve Reserve to use\n    /// @param validate If true, additional validations are applicable\n    /// @return true if trade is successful\n    function doReserveTrade(\n        ERC20 src,\n        uint amount,\n        ERC20 dest,\n        address destAddress,\n        uint expectedDestAmount,\n        KyberReserveInterface reserve,\n        uint conversionRate,\n        bool validate\n    )\n        internal\n        returns(bool)\n    {\n        uint callValue = 0;\n\n        if (src == dest) {\n            //this is for a \"fake\" trade when both src and dest are ethers.\n            if (destAddress != (address(this)))\n                destAddress.transfer(amount);\n            return true;\n        }\n\n        if (src == ETH_TOKEN_ADDRESS) {\n            callValue = amount;\n        }\n\n        // reserve sends tokens/eth to network. network sends it to destination\n        require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));\n\n        if (destAddress != address(this)) {\n            //for token to token dest address is network. and Ether / token already here...\n            if (dest == ETH_TOKEN_ADDRESS) {\n                destAddress.transfer(expectedDestAmount);\n            } else {\n                require(dest.transfer(destAddress, expectedDestAmount));\n            }\n        }\n\n        return true;\n    }\n\n    /// when user sets max dest amount we could have too many source tokens == change. so we send it back to user.\n    function handleChange (ERC20 src, uint srcAmount, uint requiredSrcAmount, address trader) internal returns (bool) {\n\n        if (requiredSrcAmount \u003c srcAmount) {\n            //if there is \"change\" send back to trader\n            if (src == ETH_TOKEN_ADDRESS) {\n                trader.transfer(srcAmount - requiredSrcAmount);\n            } else {\n                require(src.transfer(trader, (srcAmount - requiredSrcAmount)));\n            }\n        }\n\n        return true;\n    }\n\n    /// @notice use token address ETH_TOKEN_ADDRESS for ether\n    /// @dev checks that user sent ether/tokens to contract before trade\n    /// @param src Src token\n    /// @param srcAmount amount of src tokens\n    /// @return true if tradeInput is valid\n    function validateTradeInput(ERC20 src, uint srcAmount, ERC20 dest, address destAddress)\n        internal\n        view\n        returns(bool)\n    {\n        require(srcAmount \u003c= MAX_QTY);\n        require(srcAmount != 0);\n        require(destAddress != address(0));\n        require(src != dest);\n\n        if (src == ETH_TOKEN_ADDRESS) {\n            require(msg.value == srcAmount);\n        } else {\n            require(msg.value == 0);\n            //funds should have been moved to this contract already.\n            require(src.balanceOf(this) \u003e= srcAmount);\n        }\n\n        return true;\n    }\n}\n"},"KyberNetworkInterface.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\n\n\n/// @title Kyber Network interface\ninterface KyberNetworkInterface {\n    function maxGasPrice() public view returns(uint);\n    function getUserCapInWei(address user) public view returns(uint);\n    function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);\n    function enabled() public view returns(bool);\n    function info(bytes32 id) public view returns(uint);\n\n    function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view\n        returns (uint expectedRate, uint slippageRate);\n\n    function tradeWithHint(address trader, ERC20 src, uint srcAmount, ERC20 dest, address destAddress,\n        uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint);\n}\n"},"KyberReserveInterface.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\n\n/// @title Kyber Reserve contract\ninterface KyberReserveInterface {\n\n    function trade(\n        ERC20 srcToken,\n        uint srcAmount,\n        ERC20 destToken,\n        address destAddress,\n        uint conversionRate,\n        bool validate\n    )\n        public\n        payable\n        returns(bool);\n\n    function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint);\n}\n"},"PermissionGroups.sol":{"content":"pragma solidity 0.4.18;\n\n\ncontract PermissionGroups {\n\n    address public admin;\n    address public pendingAdmin;\n    mapping(address=\u003ebool) internal operators;\n    mapping(address=\u003ebool) internal alerters;\n    address[] internal operatorsGroup;\n    address[] internal alertersGroup;\n    uint constant internal MAX_GROUP_SIZE = 50;\n\n    function PermissionGroups() public {\n        admin = msg.sender;\n    }\n\n    modifier onlyAdmin() {\n        require(msg.sender == admin);\n        _;\n    }\n\n    modifier onlyOperator() {\n        require(operators[msg.sender]);\n        _;\n    }\n\n    modifier onlyAlerter() {\n        require(alerters[msg.sender]);\n        _;\n    }\n\n    function getOperators () external view returns(address[]) {\n        return operatorsGroup;\n    }\n\n    function getAlerters () external view returns(address[]) {\n        return alertersGroup;\n    }\n\n    event TransferAdminPending(address pendingAdmin);\n\n    /**\n     * @dev Allows the current admin to set the pendingAdmin address.\n     * @param newAdmin The address to transfer ownership to.\n     */\n    function transferAdmin(address newAdmin) public onlyAdmin {\n        require(newAdmin != address(0));\n        TransferAdminPending(pendingAdmin);\n        pendingAdmin = newAdmin;\n    }\n\n    /**\n     * @dev Allows the current admin to set the admin in one tx. Useful initial deployment.\n     * @param newAdmin The address to transfer ownership to.\n     */\n    function transferAdminQuickly(address newAdmin) public onlyAdmin {\n        require(newAdmin != address(0));\n        TransferAdminPending(newAdmin);\n        AdminClaimed(newAdmin, admin);\n        admin = newAdmin;\n    }\n\n    event AdminClaimed( address newAdmin, address previousAdmin);\n\n    /**\n     * @dev Allows the pendingAdmin address to finalize the change admin process.\n     */\n    function claimAdmin() public {\n        require(pendingAdmin == msg.sender);\n        AdminClaimed(pendingAdmin, admin);\n        admin = pendingAdmin;\n        pendingAdmin = address(0);\n    }\n\n    event AlerterAdded (address newAlerter, bool isAdd);\n\n    function addAlerter(address newAlerter) public onlyAdmin {\n        require(!alerters[newAlerter]); // prevent duplicates.\n        require(alertersGroup.length \u003c MAX_GROUP_SIZE);\n\n        AlerterAdded(newAlerter, true);\n        alerters[newAlerter] = true;\n        alertersGroup.push(newAlerter);\n    }\n\n    function removeAlerter (address alerter) public onlyAdmin {\n        require(alerters[alerter]);\n        alerters[alerter] = false;\n\n        for (uint i = 0; i \u003c alertersGroup.length; ++i) {\n            if (alertersGroup[i] == alerter) {\n                alertersGroup[i] = alertersGroup[alertersGroup.length - 1];\n                alertersGroup.length--;\n                AlerterAdded(alerter, false);\n                break;\n            }\n        }\n    }\n\n    event OperatorAdded(address newOperator, bool isAdd);\n\n    function addOperator(address newOperator) public onlyAdmin {\n        require(!operators[newOperator]); // prevent duplicates.\n        require(operatorsGroup.length \u003c MAX_GROUP_SIZE);\n\n        OperatorAdded(newOperator, true);\n        operators[newOperator] = true;\n        operatorsGroup.push(newOperator);\n    }\n\n    function removeOperator (address operator) public onlyAdmin {\n        require(operators[operator]);\n        operators[operator] = false;\n\n        for (uint i = 0; i \u003c operatorsGroup.length; ++i) {\n            if (operatorsGroup[i] == operator) {\n                operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];\n                operatorsGroup.length -= 1;\n                OperatorAdded(operator, false);\n                break;\n            }\n        }\n    }\n}\n"},"Utils.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\n\n\n/// @title Kyber constants contract\ncontract Utils {\n\n    ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);\n    uint  constant internal PRECISION = (10**18);\n    uint  constant internal MAX_QTY   = (10**28); // 10B tokens\n    uint  constant internal MAX_RATE  = (PRECISION * 10**6); // up to 1M tokens per ETH\n    uint  constant internal MAX_DECIMALS = 18;\n    uint  constant internal ETH_DECIMALS = 18;\n    mapping(address=\u003euint) internal decimals;\n\n    function setDecimals(ERC20 token) internal {\n        if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;\n        else decimals[token] = token.decimals();\n    }\n\n    function getDecimals(ERC20 token) internal view returns(uint) {\n        if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access\n        uint tokenDecimals = decimals[token];\n        // technically, there might be token with decimals 0\n        // moreover, very possible that old tokens have decimals 0\n        // these tokens will just have higher gas fees.\n        if(tokenDecimals == 0) return token.decimals();\n\n        return tokenDecimals;\n    }\n\n    function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {\n        require(srcQty \u003c= MAX_QTY);\n        require(rate \u003c= MAX_RATE);\n\n        if (dstDecimals \u003e= srcDecimals) {\n            require((dstDecimals - srcDecimals) \u003c= MAX_DECIMALS);\n            return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;\n        } else {\n            require((srcDecimals - dstDecimals) \u003c= MAX_DECIMALS);\n            return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));\n        }\n    }\n\n    function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {\n        require(dstQty \u003c= MAX_QTY);\n        require(rate \u003c= MAX_RATE);\n        \n        //source quantity is rounded up. to avoid dest quantity being too low.\n        uint numerator;\n        uint denominator;\n        if (srcDecimals \u003e= dstDecimals) {\n            require((srcDecimals - dstDecimals) \u003c= MAX_DECIMALS);\n            numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));\n            denominator = rate;\n        } else {\n            require((dstDecimals - srcDecimals) \u003c= MAX_DECIMALS);\n            numerator = (PRECISION * dstQty);\n            denominator = (rate * (10**(dstDecimals - srcDecimals)));\n        }\n        return (numerator + denominator - 1) / denominator; //avoid rounding down errors\n    }\n}\n"},"Utils2.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./Utils.sol\";\n\n\ncontract Utils2 is Utils {\n\n    /// @dev get the balance of a user.\n    /// @param token The token type\n    /// @return The balance\n    function getBalance(ERC20 token, address user) public view returns(uint) {\n        if (token == ETH_TOKEN_ADDRESS)\n            return user.balance;\n        else\n            return token.balanceOf(user);\n    }\n\n    function getDecimalsSafe(ERC20 token) internal returns(uint) {\n\n        if (decimals[token] == 0) {\n            setDecimals(token);\n        }\n\n        return decimals[token];\n    }\n\n    function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) {\n        return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);\n    }\n\n    function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) {\n        return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);\n    }\n\n    function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals)\n        internal pure returns(uint)\n    {\n        require(srcAmount \u003c= MAX_QTY);\n        require(destAmount \u003c= MAX_QTY);\n\n        if (dstDecimals \u003e= srcDecimals) {\n            require((dstDecimals - srcDecimals) \u003c= MAX_DECIMALS);\n            return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));\n        } else {\n            require((srcDecimals - dstDecimals) \u003c= MAX_DECIMALS);\n            return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);\n        }\n    }\n}\n"},"Utils3.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./Utils2.sol\";\n\n\ncontract Utils3 is Utils2 {\n\n    function calcDestAmountWithDecimals(uint srcDecimals, uint destDecimals, uint srcAmount, uint rate) internal pure returns(uint) {\n        return calcDstQty(srcAmount, srcDecimals, destDecimals, rate);\n    }\n\n}\n"},"WhiteListInterface.sol":{"content":"pragma solidity 0.4.18;\n\n\ncontract WhiteListInterface {\n    function getUserCapInWei(address user) external view returns (uint userCapWei);\n}\n"},"Withdrawable.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\nimport \"./PermissionGroups.sol\";\n\n\n/**\n * @title Contracts that should be able to recover tokens or ethers\n * @author Ilan Doron\n * @dev This allows to recover any tokens or Ethers received in a contract.\n * This will prevent any accidental loss of tokens.\n */\ncontract Withdrawable is PermissionGroups {\n\n    event TokenWithdraw(ERC20 token, uint amount, address sendTo);\n\n    /**\n     * @dev Withdraw all ERC20 compatible tokens\n     * @param token ERC20 The address of the token contract\n     */\n    function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {\n        require(token.transfer(sendTo, amount));\n        TokenWithdraw(token, amount, sendTo);\n    }\n\n    event EtherWithdraw(uint amount, address sendTo);\n\n    /**\n     * @dev Withdraw Ethers\n     */\n    function withdrawEther(uint amount, address sendTo) external onlyAdmin {\n        sendTo.transfer(amount);\n        EtherWithdraw(amount, sendTo);\n    }\n}\n"}}

                              File 3 of 20: MANAToken
                              pragma solidity ^0.4.11;
                              
                              contract ERC20Basic {
                                uint256 public totalSupply;
                                function balanceOf(address who) constant returns (uint256);
                                function transfer(address to, uint256 value) returns (bool);
                                event Transfer(address indexed from, address indexed to, uint256 value);
                              }
                              
                              contract Ownable {
                                address public owner;
                              
                              
                                /**
                                 * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                                 * account.
                                 */
                                function Ownable() {
                                  owner = msg.sender;
                                }
                              
                              
                                /**
                                 * @dev Throws if called by any account other than the owner.
                                 */
                                modifier onlyOwner() {
                                  require(msg.sender == owner);
                                  _;
                                }
                              
                              
                                /**
                                 * @dev Allows the current owner to transfer control of the contract to a newOwner.
                                 * @param newOwner The address to transfer ownership to.
                                 */
                                function transferOwnership(address newOwner) onlyOwner {
                                  if (newOwner != address(0)) {
                                    owner = newOwner;
                                  }
                                }
                              
                              }
                              
                              contract Pausable is Ownable {
                                event Pause();
                                event Unpause();
                              
                                bool public paused = false;
                              
                              
                                /**
                                 * @dev modifier to allow actions only when the contract IS paused
                                 */
                                modifier whenNotPaused() {
                                  require(!paused);
                                  _;
                                }
                              
                                /**
                                 * @dev modifier to allow actions only when the contract IS NOT paused
                                 */
                                modifier whenPaused {
                                  require(paused);
                                  _;
                                }
                              
                                /**
                                 * @dev called by the owner to pause, triggers stopped state
                                 */
                                function pause() onlyOwner whenNotPaused returns (bool) {
                                  paused = true;
                                  Pause();
                                  return true;
                                }
                              
                                /**
                                 * @dev called by the owner to unpause, returns to normal state
                                 */
                                function unpause() onlyOwner whenPaused returns (bool) {
                                  paused = false;
                                  Unpause();
                                  return true;
                                }
                              }
                              
                              contract ERC20 is ERC20Basic {
                                function allowance(address owner, address spender) constant returns (uint256);
                                function transferFrom(address from, address to, uint256 value) returns (bool);
                                function approve(address spender, uint256 value) returns (bool);
                                event Approval(address indexed owner, address indexed spender, uint256 value);
                              }
                              
                              library SafeMath {
                                function mul(uint256 a, uint256 b) internal constant returns (uint256) {
                                  uint256 c = a * b;
                                  assert(a == 0 || c / a == b);
                                  return c;
                                }
                              
                                function div(uint256 a, uint256 b) internal constant returns (uint256) {
                                  // assert(b > 0); // Solidity automatically throws when dividing by 0
                                  uint256 c = a / b;
                                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                                  return c;
                                }
                              
                                function sub(uint256 a, uint256 b) internal constant returns (uint256) {
                                  assert(b <= a);
                                  return a - b;
                                }
                              
                                function add(uint256 a, uint256 b) internal constant returns (uint256) {
                                  uint256 c = a + b;
                                  assert(c >= a);
                                  return c;
                                }
                              }
                              
                              contract BasicToken is ERC20Basic {
                                using SafeMath for uint256;
                              
                                mapping(address => uint256) balances;
                              
                                /**
                                * @dev transfer token for a specified address
                                * @param _to The address to transfer to.
                                * @param _value The amount to be transferred.
                                */
                                function transfer(address _to, uint256 _value) returns (bool) {
                                  balances[msg.sender] = balances[msg.sender].sub(_value);
                                  balances[_to] = balances[_to].add(_value);
                                  Transfer(msg.sender, _to, _value);
                                  return true;
                                }
                              
                                /**
                                * @dev Gets the balance of the specified address.
                                * @param _owner The address to query the the balance of. 
                                * @return An uint256 representing the amount owned by the passed address.
                                */
                                function balanceOf(address _owner) constant returns (uint256 balance) {
                                  return balances[_owner];
                                }
                              
                              }
                              
                              contract StandardToken is ERC20, BasicToken {
                              
                                mapping (address => mapping (address => uint256)) allowed;
                              
                              
                                /**
                                 * @dev Transfer tokens from one address to another
                                 * @param _from address The address which you want to send tokens from
                                 * @param _to address The address which you want to transfer to
                                 * @param _value uint256 the amout of tokens to be transfered
                                 */
                                function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
                                  var _allowance = allowed[_from][msg.sender];
                              
                                  // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
                                  // require (_value <= _allowance);
                              
                                  balances[_to] = balances[_to].add(_value);
                                  balances[_from] = balances[_from].sub(_value);
                                  allowed[_from][msg.sender] = _allowance.sub(_value);
                                  Transfer(_from, _to, _value);
                                  return true;
                                }
                              
                                /**
                                 * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
                                 * @param _spender The address which will spend the funds.
                                 * @param _value The amount of tokens to be spent.
                                 */
                                function approve(address _spender, uint256 _value) returns (bool) {
                              
                                  // To change the approve amount you first have to reduce the addresses`
                                  //  allowance to zero by calling `approve(_spender, 0)` if it is not
                                  //  already 0 to mitigate the race condition described here:
                                  //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                  require((_value == 0) || (allowed[msg.sender][_spender] == 0));
                              
                                  allowed[msg.sender][_spender] = _value;
                                  Approval(msg.sender, _spender, _value);
                                  return true;
                                }
                              
                                /**
                                 * @dev Function to check the amount of tokens that an owner allowed to a spender.
                                 * @param _owner address The address which owns the funds.
                                 * @param _spender address The address which will spend the funds.
                                 * @return A uint256 specifing the amount of tokens still avaible for the spender.
                                 */
                                function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
                                  return allowed[_owner][_spender];
                                }
                              
                              }
                              
                              contract MintableToken is StandardToken, Ownable {
                                event Mint(address indexed to, uint256 amount);
                                event MintFinished();
                              
                                bool public mintingFinished = false;
                              
                              
                                modifier canMint() {
                                  require(!mintingFinished);
                                  _;
                                }
                              
                                /**
                                 * @dev Function to mint tokens
                                 * @param _to The address that will recieve the minted tokens.
                                 * @param _amount The amount of tokens to mint.
                                 * @return A boolean that indicates if the operation was successful.
                                 */
                                function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
                                  totalSupply = totalSupply.add(_amount);
                                  balances[_to] = balances[_to].add(_amount);
                                  Mint(_to, _amount);
                                  return true;
                                }
                              
                                /**
                                 * @dev Function to stop minting new tokens.
                                 * @return True if the operation was successful.
                                 */
                                function finishMinting() onlyOwner returns (bool) {
                                  mintingFinished = true;
                                  MintFinished();
                                  return true;
                                }
                              }
                              
                              contract PausableToken is StandardToken, Pausable {
                              
                                function transfer(address _to, uint _value) whenNotPaused returns (bool) {
                                  return super.transfer(_to, _value);
                                }
                              
                                function transferFrom(address _from, address _to, uint _value) whenNotPaused returns (bool) {
                                  return super.transferFrom(_from, _to, _value);
                                }
                              }
                              
                              contract BurnableToken is StandardToken {
                              
                                  event Burn(address indexed burner, uint256 value);
                              
                                  /**
                                   * @dev Burns a specified amount of tokens.
                                   * @param _value The amount of tokens to burn. 
                                   */
                                  function burn(uint256 _value) public {
                                      require(_value > 0);
                              
                                      address burner = msg.sender;
                                      balances[burner] = balances[burner].sub(_value);
                                      totalSupply = totalSupply.sub(_value);
                                      Burn(msg.sender, _value);
                                  }
                              
                              }
                              
                              contract MANAToken is BurnableToken, PausableToken, MintableToken {
                              
                                  string public constant symbol = "MANA";
                              
                                  string public constant name = "Decentraland MANA";
                              
                                  uint8 public constant decimals = 18;
                              
                                  function burn(uint256 _value) whenNotPaused public {
                                      super.burn(_value);
                                  }
                              }

                              File 4 of 20: FeeBurner
                              {"ERC20Interface.sol":{"content":"pragma solidity 0.4.18;\n\n\n// https://github.com/ethereum/EIPs/issues/20\ninterface ERC20 {\n    function totalSupply() public view returns (uint supply);\n    function balanceOf(address _owner) public view returns (uint balance);\n    function transfer(address _to, uint _value) public returns (bool success);\n    function transferFrom(address _from, address _to, uint _value) public returns (bool success);\n    function approve(address _spender, uint _value) public returns (bool success);\n    function allowance(address _owner, address _spender) public view returns (uint remaining);\n    function decimals() public view returns(uint digits);\n    event Approval(address indexed _owner, address indexed _spender, uint _value);\n}\n"},"FeeBurner.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./FeeBurnerInterface.sol\";\nimport \"./Withdrawable.sol\";\nimport \"./Utils3.sol\";\nimport \"./KyberNetworkInterface.sol\";\n\n\ninterface BurnableToken {\n    function transferFrom(address _from, address _to, uint _value) public returns (bool);\n    function burnFrom(address _from, uint256 _value) public returns (bool);\n}\n\n\ncontract FeeBurner is Withdrawable, FeeBurnerInterface, Utils3 {\n\n    mapping(address=\u003euint) public reserveFeesInBps;\n    mapping(address=\u003eaddress) public reserveKNCWallet; //wallet holding knc per reserve. from here burn and send fees.\n    mapping(address=\u003euint) public walletFeesInBps; // wallet that is the source of tx is entitled so some fees.\n    mapping(address=\u003euint) public reserveFeeToBurn;\n    mapping(address=\u003euint) public feePayedPerReserve; // track burned fees and sent wallet fees per reserve.\n    mapping(address=\u003emapping(address=\u003euint)) public reserveFeeToWallet;\n    address public taxWallet;\n    uint public taxFeeBps = 0; // burned fees are taxed. % out of burned fees.\n\n    BurnableToken public knc;\n    KyberNetworkInterface public kyberNetwork;\n    uint public kncPerEthRatePrecision = 600 * PRECISION; //--\u003e 1 ether = 600 knc tokens\n\n    function FeeBurner(\n        address _admin,\n        BurnableToken _kncToken,\n        KyberNetworkInterface _kyberNetwork,\n        uint _initialKncToEthRatePrecision\n    )\n        public\n    {\n        require(_admin != address(0));\n        require(_kncToken != address(0));\n        require(_kyberNetwork != address(0));\n        require(_initialKncToEthRatePrecision != 0);\n\n        kyberNetwork = _kyberNetwork;\n        admin = _admin;\n        knc = _kncToken;\n        kncPerEthRatePrecision = _initialKncToEthRatePrecision;\n    }\n\n    event ReserveDataSet(address reserve, uint feeInBps, address kncWallet);\n\n    function setReserveData(address reserve, uint feesInBps, address kncWallet) public onlyOperator {\n        require(feesInBps \u003c 100); // make sure it is always \u003c 1%\n        require(kncWallet != address(0));\n        reserveFeesInBps[reserve] = feesInBps;\n        reserveKNCWallet[reserve] = kncWallet;\n        ReserveDataSet(reserve, feesInBps, kncWallet);\n    }\n\n    event WalletFeesSet(address wallet, uint feesInBps);\n\n    function setWalletFees(address wallet, uint feesInBps) public onlyAdmin {\n        require(feesInBps \u003c 10000); // under 100%\n        walletFeesInBps[wallet] = feesInBps;\n        WalletFeesSet(wallet, feesInBps);\n    }\n\n    event TaxFeesSet(uint feesInBps);\n\n    function setTaxInBps(uint _taxFeeBps) public onlyAdmin {\n        require(_taxFeeBps \u003c 10000); // under 100%\n        taxFeeBps = _taxFeeBps;\n        TaxFeesSet(_taxFeeBps);\n    }\n\n    event TaxWalletSet(address taxWallet);\n\n    function setTaxWallet(address _taxWallet) public onlyAdmin {\n        require(_taxWallet != address(0));\n        taxWallet = _taxWallet;\n        TaxWalletSet(_taxWallet);\n    }\n\n    event KNCRateSet(uint ethToKncRatePrecision, uint kyberEthKnc, uint kyberKncEth, address updater);\n\n    function setKNCRate() public {\n        //query kyber for knc rate sell and buy\n        uint kyberEthKncRate;\n        uint kyberKncEthRate;\n        (kyberEthKncRate, ) = kyberNetwork.getExpectedRate(ETH_TOKEN_ADDRESS, ERC20(knc), (10 ** 18));\n        (kyberKncEthRate, ) = kyberNetwork.getExpectedRate(ERC20(knc), ETH_TOKEN_ADDRESS, (10 ** 18));\n\n        //check \"reasonable\" spread == diff not too big. rate wasn\u0027t tampered.\n        require(kyberEthKncRate * kyberKncEthRate \u003c PRECISION ** 2 * 2);\n        require(kyberEthKncRate * kyberKncEthRate \u003e PRECISION ** 2 / 2);\n\n        require(kyberEthKncRate \u003c= MAX_RATE);\n        kncPerEthRatePrecision = kyberEthKncRate;\n        KNCRateSet(kncPerEthRatePrecision, kyberEthKncRate, kyberKncEthRate, msg.sender);\n    }\n\n    event AssignFeeToWallet(address reserve, address wallet, uint walletFee);\n    event AssignBurnFees(address reserve, uint burnFee);\n\n    function handleFees(uint tradeWeiAmount, address reserve, address wallet) public returns(bool) {\n        require(msg.sender == address(kyberNetwork));\n        require(tradeWeiAmount \u003c= MAX_QTY);\n\n        // MAX_DECIMALS = 18 = KNC_DECIMALS, use this value instead of calling getDecimals() to save gas\n        uint kncAmount = calcDestAmountWithDecimals(ETH_DECIMALS, MAX_DECIMALS, tradeWeiAmount, kncPerEthRatePrecision);\n        uint fee = kncAmount * reserveFeesInBps[reserve] / 10000;\n\n        uint walletFee = fee * walletFeesInBps[wallet] / 10000;\n        require(fee \u003e= walletFee);\n        uint feeToBurn = fee - walletFee;\n\n        if (walletFee \u003e 0) {\n            reserveFeeToWallet[reserve][wallet] += walletFee;\n            AssignFeeToWallet(reserve, wallet, walletFee);\n        }\n\n        if (feeToBurn \u003e 0) {\n            AssignBurnFees(reserve, feeToBurn);\n            reserveFeeToBurn[reserve] += feeToBurn;\n        }\n\n        return true;\n    }\n\n    event BurnAssignedFees(address indexed reserve, address sender, uint quantity);\n\n    event SendTaxFee(address indexed reserve, address sender, address taxWallet, uint quantity);\n\n    // this function is callable by anyone\n    function burnReserveFees(address reserve) public {\n        uint burnAmount = reserveFeeToBurn[reserve];\n        uint taxToSend = 0;\n        require(burnAmount \u003e 2);\n        reserveFeeToBurn[reserve] = 1; // leave 1 twei to avoid spikes in gas fee\n        if (taxWallet != address(0) \u0026\u0026 taxFeeBps != 0) {\n            taxToSend = (burnAmount - 1) * taxFeeBps / 10000;\n            require(burnAmount - 1 \u003e taxToSend);\n            burnAmount -= taxToSend;\n            if (taxToSend \u003e 0) {\n                require(knc.transferFrom(reserveKNCWallet[reserve], taxWallet, taxToSend));\n                SendTaxFee(reserve, msg.sender, taxWallet, taxToSend);\n            }\n        }\n        require(knc.burnFrom(reserveKNCWallet[reserve], burnAmount - 1));\n\n        //update reserve \"payments\" so far\n        feePayedPerReserve[reserve] += (taxToSend + burnAmount - 1);\n\n        BurnAssignedFees(reserve, msg.sender, (burnAmount - 1));\n    }\n\n    event SendWalletFees(address indexed wallet, address reserve, address sender);\n\n    // this function is callable by anyone\n    function sendFeeToWallet(address wallet, address reserve) public {\n        uint feeAmount = reserveFeeToWallet[reserve][wallet];\n        require(feeAmount \u003e 1);\n        reserveFeeToWallet[reserve][wallet] = 1; // leave 1 twei to avoid spikes in gas fee\n        require(knc.transferFrom(reserveKNCWallet[reserve], wallet, feeAmount - 1));\n\n        feePayedPerReserve[reserve] += (feeAmount - 1);\n        SendWalletFees(wallet, reserve, msg.sender);\n    }\n}\n"},"FeeBurnerInterface.sol":{"content":"pragma solidity 0.4.18;\n\n\ninterface FeeBurnerInterface {\n    function handleFees (uint tradeWeiAmount, address reserve, address wallet) public returns(bool);\n    function setReserveData(address reserve, uint feesInBps, address kncWallet) public;\n}\n"},"KyberNetworkInterface.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\n\n\n/// @title Kyber Network interface\ninterface KyberNetworkInterface {\n    function maxGasPrice() public view returns(uint);\n    function getUserCapInWei(address user) public view returns(uint);\n    function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);\n    function enabled() public view returns(bool);\n    function info(bytes32 id) public view returns(uint);\n\n    function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view\n        returns (uint expectedRate, uint slippageRate);\n\n    function tradeWithHint(address trader, ERC20 src, uint srcAmount, ERC20 dest, address destAddress,\n        uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint);\n}\n"},"PermissionGroups.sol":{"content":"pragma solidity 0.4.18;\n\n\ncontract PermissionGroups {\n\n    address public admin;\n    address public pendingAdmin;\n    mapping(address=\u003ebool) internal operators;\n    mapping(address=\u003ebool) internal alerters;\n    address[] internal operatorsGroup;\n    address[] internal alertersGroup;\n    uint constant internal MAX_GROUP_SIZE = 50;\n\n    function PermissionGroups() public {\n        admin = msg.sender;\n    }\n\n    modifier onlyAdmin() {\n        require(msg.sender == admin);\n        _;\n    }\n\n    modifier onlyOperator() {\n        require(operators[msg.sender]);\n        _;\n    }\n\n    modifier onlyAlerter() {\n        require(alerters[msg.sender]);\n        _;\n    }\n\n    function getOperators () external view returns(address[]) {\n        return operatorsGroup;\n    }\n\n    function getAlerters () external view returns(address[]) {\n        return alertersGroup;\n    }\n\n    event TransferAdminPending(address pendingAdmin);\n\n    /**\n     * @dev Allows the current admin to set the pendingAdmin address.\n     * @param newAdmin The address to transfer ownership to.\n     */\n    function transferAdmin(address newAdmin) public onlyAdmin {\n        require(newAdmin != address(0));\n        TransferAdminPending(pendingAdmin);\n        pendingAdmin = newAdmin;\n    }\n\n    /**\n     * @dev Allows the current admin to set the admin in one tx. Useful initial deployment.\n     * @param newAdmin The address to transfer ownership to.\n     */\n    function transferAdminQuickly(address newAdmin) public onlyAdmin {\n        require(newAdmin != address(0));\n        TransferAdminPending(newAdmin);\n        AdminClaimed(newAdmin, admin);\n        admin = newAdmin;\n    }\n\n    event AdminClaimed( address newAdmin, address previousAdmin);\n\n    /**\n     * @dev Allows the pendingAdmin address to finalize the change admin process.\n     */\n    function claimAdmin() public {\n        require(pendingAdmin == msg.sender);\n        AdminClaimed(pendingAdmin, admin);\n        admin = pendingAdmin;\n        pendingAdmin = address(0);\n    }\n\n    event AlerterAdded (address newAlerter, bool isAdd);\n\n    function addAlerter(address newAlerter) public onlyAdmin {\n        require(!alerters[newAlerter]); // prevent duplicates.\n        require(alertersGroup.length \u003c MAX_GROUP_SIZE);\n\n        AlerterAdded(newAlerter, true);\n        alerters[newAlerter] = true;\n        alertersGroup.push(newAlerter);\n    }\n\n    function removeAlerter (address alerter) public onlyAdmin {\n        require(alerters[alerter]);\n        alerters[alerter] = false;\n\n        for (uint i = 0; i \u003c alertersGroup.length; ++i) {\n            if (alertersGroup[i] == alerter) {\n                alertersGroup[i] = alertersGroup[alertersGroup.length - 1];\n                alertersGroup.length--;\n                AlerterAdded(alerter, false);\n                break;\n            }\n        }\n    }\n\n    event OperatorAdded(address newOperator, bool isAdd);\n\n    function addOperator(address newOperator) public onlyAdmin {\n        require(!operators[newOperator]); // prevent duplicates.\n        require(operatorsGroup.length \u003c MAX_GROUP_SIZE);\n\n        OperatorAdded(newOperator, true);\n        operators[newOperator] = true;\n        operatorsGroup.push(newOperator);\n    }\n\n    function removeOperator (address operator) public onlyAdmin {\n        require(operators[operator]);\n        operators[operator] = false;\n\n        for (uint i = 0; i \u003c operatorsGroup.length; ++i) {\n            if (operatorsGroup[i] == operator) {\n                operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];\n                operatorsGroup.length -= 1;\n                OperatorAdded(operator, false);\n                break;\n            }\n        }\n    }\n}\n"},"Utils.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\n\n\n/// @title Kyber constants contract\ncontract Utils {\n\n    ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);\n    uint  constant internal PRECISION = (10**18);\n    uint  constant internal MAX_QTY   = (10**28); // 10B tokens\n    uint  constant internal MAX_RATE  = (PRECISION * 10**6); // up to 1M tokens per ETH\n    uint  constant internal MAX_DECIMALS = 18;\n    uint  constant internal ETH_DECIMALS = 18;\n    mapping(address=\u003euint) internal decimals;\n\n    function setDecimals(ERC20 token) internal {\n        if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;\n        else decimals[token] = token.decimals();\n    }\n\n    function getDecimals(ERC20 token) internal view returns(uint) {\n        if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access\n        uint tokenDecimals = decimals[token];\n        // technically, there might be token with decimals 0\n        // moreover, very possible that old tokens have decimals 0\n        // these tokens will just have higher gas fees.\n        if(tokenDecimals == 0) return token.decimals();\n\n        return tokenDecimals;\n    }\n\n    function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {\n        require(srcQty \u003c= MAX_QTY);\n        require(rate \u003c= MAX_RATE);\n\n        if (dstDecimals \u003e= srcDecimals) {\n            require((dstDecimals - srcDecimals) \u003c= MAX_DECIMALS);\n            return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;\n        } else {\n            require((srcDecimals - dstDecimals) \u003c= MAX_DECIMALS);\n            return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));\n        }\n    }\n\n    function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {\n        require(dstQty \u003c= MAX_QTY);\n        require(rate \u003c= MAX_RATE);\n        \n        //source quantity is rounded up. to avoid dest quantity being too low.\n        uint numerator;\n        uint denominator;\n        if (srcDecimals \u003e= dstDecimals) {\n            require((srcDecimals - dstDecimals) \u003c= MAX_DECIMALS);\n            numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));\n            denominator = rate;\n        } else {\n            require((dstDecimals - srcDecimals) \u003c= MAX_DECIMALS);\n            numerator = (PRECISION * dstQty);\n            denominator = (rate * (10**(dstDecimals - srcDecimals)));\n        }\n        return (numerator + denominator - 1) / denominator; //avoid rounding down errors\n    }\n}\n"},"Utils2.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./Utils.sol\";\n\n\ncontract Utils2 is Utils {\n\n    /// @dev get the balance of a user.\n    /// @param token The token type\n    /// @return The balance\n    function getBalance(ERC20 token, address user) public view returns(uint) {\n        if (token == ETH_TOKEN_ADDRESS)\n            return user.balance;\n        else\n            return token.balanceOf(user);\n    }\n\n    function getDecimalsSafe(ERC20 token) internal returns(uint) {\n\n        if (decimals[token] == 0) {\n            setDecimals(token);\n        }\n\n        return decimals[token];\n    }\n\n    function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) {\n        return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);\n    }\n\n    function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) {\n        return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);\n    }\n\n    function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals)\n        internal pure returns(uint)\n    {\n        require(srcAmount \u003c= MAX_QTY);\n        require(destAmount \u003c= MAX_QTY);\n\n        if (dstDecimals \u003e= srcDecimals) {\n            require((dstDecimals - srcDecimals) \u003c= MAX_DECIMALS);\n            return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));\n        } else {\n            require((srcDecimals - dstDecimals) \u003c= MAX_DECIMALS);\n            return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);\n        }\n    }\n}\n"},"Utils3.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./Utils2.sol\";\n\n\ncontract Utils3 is Utils2 {\n\n    function calcDestAmountWithDecimals(uint srcDecimals, uint destDecimals, uint srcAmount, uint rate) internal pure returns(uint) {\n        return calcDstQty(srcAmount, srcDecimals, destDecimals, rate);\n    }\n\n}\n"},"Withdrawable.sol":{"content":"pragma solidity 0.4.18;\n\n\nimport \"./ERC20Interface.sol\";\nimport \"./PermissionGroups.sol\";\n\n\n/**\n * @title Contracts that should be able to recover tokens or ethers\n * @author Ilan Doron\n * @dev This allows to recover any tokens or Ethers received in a contract.\n * This will prevent any accidental loss of tokens.\n */\ncontract Withdrawable is PermissionGroups {\n\n    event TokenWithdraw(ERC20 token, uint amount, address sendTo);\n\n    /**\n     * @dev Withdraw all ERC20 compatible tokens\n     * @param token ERC20 The address of the token contract\n     */\n    function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {\n        require(token.transfer(sendTo, amount));\n        TokenWithdraw(token, amount, sendTo);\n    }\n\n    event EtherWithdraw(uint amount, address sendTo);\n\n    /**\n     * @dev Withdraw Ethers\n     */\n    function withdrawEther(uint amount, address sendTo) external onlyAdmin {\n        sendTo.transfer(amount);\n        EtherWithdraw(amount, sendTo);\n    }\n}\n"}}

                              File 5 of 20: KyberNetworkProxy
                              pragma solidity 0.4.18;
                              
                              // File: contracts/ERC20Interface.sol
                              
                              // https://github.com/ethereum/EIPs/issues/20
                              interface ERC20 {
                                  function totalSupply() public view returns (uint supply);
                                  function balanceOf(address _owner) public view returns (uint balance);
                                  function transfer(address _to, uint _value) public returns (bool success);
                                  function transferFrom(address _from, address _to, uint _value) public returns (bool success);
                                  function approve(address _spender, uint _value) public returns (bool success);
                                  function allowance(address _owner, address _spender) public view returns (uint remaining);
                                  function decimals() public view returns(uint digits);
                                  event Approval(address indexed _owner, address indexed _spender, uint _value);
                              }
                              
                              // File: contracts/KyberNetworkInterface.sol
                              
                              /// @title Kyber Network interface
                              interface KyberNetworkInterface {
                                  function maxGasPrice() public view returns(uint);
                                  function getUserCapInWei(address user) public view returns(uint);
                                  function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);
                                  function enabled() public view returns(bool);
                                  function info(bytes32 id) public view returns(uint);
                              
                                  function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view
                                      returns (uint expectedRate, uint slippageRate);
                              
                                  function tradeWithHint(address trader, ERC20 src, uint srcAmount, ERC20 dest, address destAddress,
                                      uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint);
                              }
                              
                              // File: contracts/KyberNetworkProxyInterface.sol
                              
                              /// @title Kyber Network interface
                              interface KyberNetworkProxyInterface {
                                  function maxGasPrice() public view returns(uint);
                                  function getUserCapInWei(address user) public view returns(uint);
                                  function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint);
                                  function enabled() public view returns(bool);
                                  function info(bytes32 id) public view returns(uint);
                              
                                  function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view
                                      returns (uint expectedRate, uint slippageRate);
                              
                                  function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount,
                                      uint minConversionRate, address walletId, bytes hint) public payable returns(uint);
                              }
                              
                              // File: contracts/SimpleNetworkInterface.sol
                              
                              /// @title simple interface for Kyber Network 
                              interface SimpleNetworkInterface {
                                  function swapTokenToToken(ERC20 src, uint srcAmount, ERC20 dest, uint minConversionRate) public returns(uint);
                                  function swapEtherToToken(ERC20 token, uint minConversionRate) public payable returns(uint);
                                  function swapTokenToEther(ERC20 token, uint srcAmount, uint minConversionRate) public returns(uint);
                              }
                              
                              // File: contracts/Utils.sol
                              
                              /// @title Kyber constants contract
                              contract Utils {
                              
                                  ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
                                  uint  constant internal PRECISION = (10**18);
                                  uint  constant internal MAX_QTY   = (10**28); // 10B tokens
                                  uint  constant internal MAX_RATE  = (PRECISION * 10**6); // up to 1M tokens per ETH
                                  uint  constant internal MAX_DECIMALS = 18;
                                  uint  constant internal ETH_DECIMALS = 18;
                                  mapping(address=>uint) internal decimals;
                              
                                  function setDecimals(ERC20 token) internal {
                                      if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
                                      else decimals[token] = token.decimals();
                                  }
                              
                                  function getDecimals(ERC20 token) internal view returns(uint) {
                                      if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
                                      uint tokenDecimals = decimals[token];
                                      // technically, there might be token with decimals 0
                                      // moreover, very possible that old tokens have decimals 0
                                      // these tokens will just have higher gas fees.
                                      if(tokenDecimals == 0) return token.decimals();
                              
                                      return tokenDecimals;
                                  }
                              
                                  function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
                                      require(srcQty <= MAX_QTY);
                                      require(rate <= MAX_RATE);
                              
                                      if (dstDecimals >= srcDecimals) {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
                                      } else {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
                                      }
                                  }
                              
                                  function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
                                      require(dstQty <= MAX_QTY);
                                      require(rate <= MAX_RATE);
                                      
                                      //source quantity is rounded up. to avoid dest quantity being too low.
                                      uint numerator;
                                      uint denominator;
                                      if (srcDecimals >= dstDecimals) {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
                                          denominator = rate;
                                      } else {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          numerator = (PRECISION * dstQty);
                                          denominator = (rate * (10**(dstDecimals - srcDecimals)));
                                      }
                                      return (numerator + denominator - 1) / denominator; //avoid rounding down errors
                                  }
                              }
                              
                              // File: contracts/Utils2.sol
                              
                              contract Utils2 is Utils {
                              
                                  /// @dev get the balance of a user.
                                  /// @param token The token type
                                  /// @return The balance
                                  function getBalance(ERC20 token, address user) public view returns(uint) {
                                      if (token == ETH_TOKEN_ADDRESS)
                                          return user.balance;
                                      else
                                          return token.balanceOf(user);
                                  }
                              
                                  function getDecimalsSafe(ERC20 token) internal returns(uint) {
                              
                                      if (decimals[token] == 0) {
                                          setDecimals(token);
                                      }
                              
                                      return decimals[token];
                                  }
                              
                                  function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) {
                                      return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
                                  }
                              
                                  function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) {
                                      return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
                                  }
                              
                                  function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals)
                                      internal pure returns(uint)
                                  {
                                      require(srcAmount <= MAX_QTY);
                                      require(destAmount <= MAX_QTY);
                              
                                      if (dstDecimals >= srcDecimals) {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
                                      } else {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
                                      }
                                  }
                              }
                              
                              // File: contracts/PermissionGroups.sol
                              
                              contract PermissionGroups {
                              
                                  address public admin;
                                  address public pendingAdmin;
                                  mapping(address=>bool) internal operators;
                                  mapping(address=>bool) internal alerters;
                                  address[] internal operatorsGroup;
                                  address[] internal alertersGroup;
                                  uint constant internal MAX_GROUP_SIZE = 50;
                              
                                  function PermissionGroups() public {
                                      admin = msg.sender;
                                  }
                              
                                  modifier onlyAdmin() {
                                      require(msg.sender == admin);
                                      _;
                                  }
                              
                                  modifier onlyOperator() {
                                      require(operators[msg.sender]);
                                      _;
                                  }
                              
                                  modifier onlyAlerter() {
                                      require(alerters[msg.sender]);
                                      _;
                                  }
                              
                                  function getOperators () external view returns(address[]) {
                                      return operatorsGroup;
                                  }
                              
                                  function getAlerters () external view returns(address[]) {
                                      return alertersGroup;
                                  }
                              
                                  event TransferAdminPending(address pendingAdmin);
                              
                                  /**
                                   * @dev Allows the current admin to set the pendingAdmin address.
                                   * @param newAdmin The address to transfer ownership to.
                                   */
                                  function transferAdmin(address newAdmin) public onlyAdmin {
                                      require(newAdmin != address(0));
                                      TransferAdminPending(pendingAdmin);
                                      pendingAdmin = newAdmin;
                                  }
                              
                                  /**
                                   * @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
                                   * @param newAdmin The address to transfer ownership to.
                                   */
                                  function transferAdminQuickly(address newAdmin) public onlyAdmin {
                                      require(newAdmin != address(0));
                                      TransferAdminPending(newAdmin);
                                      AdminClaimed(newAdmin, admin);
                                      admin = newAdmin;
                                  }
                              
                                  event AdminClaimed( address newAdmin, address previousAdmin);
                              
                                  /**
                                   * @dev Allows the pendingAdmin address to finalize the change admin process.
                                   */
                                  function claimAdmin() public {
                                      require(pendingAdmin == msg.sender);
                                      AdminClaimed(pendingAdmin, admin);
                                      admin = pendingAdmin;
                                      pendingAdmin = address(0);
                                  }
                              
                                  event AlerterAdded (address newAlerter, bool isAdd);
                              
                                  function addAlerter(address newAlerter) public onlyAdmin {
                                      require(!alerters[newAlerter]); // prevent duplicates.
                                      require(alertersGroup.length < MAX_GROUP_SIZE);
                              
                                      AlerterAdded(newAlerter, true);
                                      alerters[newAlerter] = true;
                                      alertersGroup.push(newAlerter);
                                  }
                              
                                  function removeAlerter (address alerter) public onlyAdmin {
                                      require(alerters[alerter]);
                                      alerters[alerter] = false;
                              
                                      for (uint i = 0; i < alertersGroup.length; ++i) {
                                          if (alertersGroup[i] == alerter) {
                                              alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
                                              alertersGroup.length--;
                                              AlerterAdded(alerter, false);
                                              break;
                                          }
                                      }
                                  }
                              
                                  event OperatorAdded(address newOperator, bool isAdd);
                              
                                  function addOperator(address newOperator) public onlyAdmin {
                                      require(!operators[newOperator]); // prevent duplicates.
                                      require(operatorsGroup.length < MAX_GROUP_SIZE);
                              
                                      OperatorAdded(newOperator, true);
                                      operators[newOperator] = true;
                                      operatorsGroup.push(newOperator);
                                  }
                              
                                  function removeOperator (address operator) public onlyAdmin {
                                      require(operators[operator]);
                                      operators[operator] = false;
                              
                                      for (uint i = 0; i < operatorsGroup.length; ++i) {
                                          if (operatorsGroup[i] == operator) {
                                              operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
                                              operatorsGroup.length -= 1;
                                              OperatorAdded(operator, false);
                                              break;
                                          }
                                      }
                                  }
                              }
                              
                              // File: contracts/Withdrawable.sol
                              
                              /**
                               * @title Contracts that should be able to recover tokens or ethers
                               * @author Ilan Doron
                               * @dev This allows to recover any tokens or Ethers received in a contract.
                               * This will prevent any accidental loss of tokens.
                               */
                              contract Withdrawable is PermissionGroups {
                              
                                  event TokenWithdraw(ERC20 token, uint amount, address sendTo);
                              
                                  /**
                                   * @dev Withdraw all ERC20 compatible tokens
                                   * @param token ERC20 The address of the token contract
                                   */
                                  function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
                                      require(token.transfer(sendTo, amount));
                                      TokenWithdraw(token, amount, sendTo);
                                  }
                              
                                  event EtherWithdraw(uint amount, address sendTo);
                              
                                  /**
                                   * @dev Withdraw Ethers
                                   */
                                  function withdrawEther(uint amount, address sendTo) external onlyAdmin {
                                      sendTo.transfer(amount);
                                      EtherWithdraw(amount, sendTo);
                                  }
                              }
                              
                              // File: contracts/KyberNetworkProxy.sol
                              
                              ////////////////////////////////////////////////////////////////////////////////////////////////////////
                              /// @title Kyber Network proxy for main contract
                              contract KyberNetworkProxy is KyberNetworkProxyInterface, SimpleNetworkInterface, Withdrawable, Utils2 {
                              
                                  KyberNetworkInterface public kyberNetworkContract;
                              
                                  function KyberNetworkProxy(address _admin) public {
                                      require(_admin != address(0));
                                      admin = _admin;
                                  }
                              
                                  /// @notice use token address ETH_TOKEN_ADDRESS for ether
                                  /// @dev makes a trade between src and dest token and send dest token to destAddress
                                  /// @param src Src token
                                  /// @param srcAmount amount of src tokens
                                  /// @param dest   Destination token
                                  /// @param destAddress Address to send tokens to
                                  /// @param maxDestAmount A limit on the amount of dest tokens
                                  /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
                                  /// @param walletId is the wallet ID to send part of the fees
                                  /// @return amount of actual dest tokens
                                  function trade(
                                      ERC20 src,
                                      uint srcAmount,
                                      ERC20 dest,
                                      address destAddress,
                                      uint maxDestAmount,
                                      uint minConversionRate,
                                      address walletId
                                  )
                                      public
                                      payable
                                      returns(uint)
                                  {
                                      bytes memory hint;
                              
                                      return tradeWithHint(
                                          src,
                                          srcAmount,
                                          dest,
                                          destAddress,
                                          maxDestAmount,
                                          minConversionRate,
                                          walletId,
                                          hint
                                      );
                                  }
                              
                                  /// @dev makes a trade between src and dest token and send dest tokens to msg sender
                                  /// @param src Src token
                                  /// @param srcAmount amount of src tokens
                                  /// @param dest Destination token
                                  /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
                                  /// @return amount of actual dest tokens
                                  function swapTokenToToken(
                                      ERC20 src,
                                      uint srcAmount,
                                      ERC20 dest,
                                      uint minConversionRate
                                  )
                                      public
                                      returns(uint)
                                  {
                                      bytes memory hint;
                              
                                      return tradeWithHint(
                                          src,
                                          srcAmount,
                                          dest,
                                          msg.sender,
                                          MAX_QTY,
                                          minConversionRate,
                                          0,
                                          hint
                                      );
                                  }
                              
                                  /// @dev makes a trade from Ether to token. Sends token to msg sender
                                  /// @param token Destination token
                                  /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
                                  /// @return amount of actual dest tokens
                                  function swapEtherToToken(ERC20 token, uint minConversionRate) public payable returns(uint) {
                                      bytes memory hint;
                              
                                      return tradeWithHint(
                                          ETH_TOKEN_ADDRESS,
                                          msg.value,
                                          token,
                                          msg.sender,
                                          MAX_QTY,
                                          minConversionRate,
                                          0,
                                          hint
                                      );
                                  }
                              
                                  /// @dev makes a trade from token to Ether, sends Ether to msg sender
                                  /// @param token Src token
                                  /// @param srcAmount amount of src tokens
                                  /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
                                  /// @return amount of actual dest tokens
                                  function swapTokenToEther(ERC20 token, uint srcAmount, uint minConversionRate) public returns(uint) {
                                      bytes memory hint;
                              
                                      return tradeWithHint(
                                          token,
                                          srcAmount,
                                          ETH_TOKEN_ADDRESS,
                                          msg.sender,
                                          MAX_QTY,
                                          minConversionRate,
                                          0,
                                          hint
                                      );
                                  }
                              
                                  struct UserBalance {
                                      uint srcBalance;
                                      uint destBalance;
                                  }
                              
                                  event ExecuteTrade(address indexed trader, ERC20 src, ERC20 dest, uint actualSrcAmount, uint actualDestAmount);
                              
                                  /// @notice use token address ETH_TOKEN_ADDRESS for ether
                                  /// @dev makes a trade between src and dest token and send dest token to destAddress
                                  /// @param src Src token
                                  /// @param srcAmount amount of src tokens
                                  /// @param dest Destination token
                                  /// @param destAddress Address to send tokens to
                                  /// @param maxDestAmount A limit on the amount of dest tokens
                                  /// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
                                  /// @param walletId is the wallet ID to send part of the fees
                                  /// @param hint will give hints for the trade.
                                  /// @return amount of actual dest tokens
                                  function tradeWithHint(
                                      ERC20 src,
                                      uint srcAmount,
                                      ERC20 dest,
                                      address destAddress,
                                      uint maxDestAmount,
                                      uint minConversionRate,
                                      address walletId,
                                      bytes hint
                                  )
                                      public
                                      payable
                                      returns(uint)
                                  {
                                      require(src == ETH_TOKEN_ADDRESS || msg.value == 0);
                                      
                                      UserBalance memory userBalanceBefore;
                              
                                      userBalanceBefore.srcBalance = getBalance(src, msg.sender);
                                      userBalanceBefore.destBalance = getBalance(dest, destAddress);
                              
                                      if (src == ETH_TOKEN_ADDRESS) {
                                          userBalanceBefore.srcBalance += msg.value;
                                      } else {
                                          require(src.transferFrom(msg.sender, kyberNetworkContract, srcAmount));
                                      }
                              
                                      uint reportedDestAmount = kyberNetworkContract.tradeWithHint.value(msg.value)(
                                          msg.sender,
                                          src,
                                          srcAmount,
                                          dest,
                                          destAddress,
                                          maxDestAmount,
                                          minConversionRate,
                                          walletId,
                                          hint
                                      );
                              
                                      TradeOutcome memory tradeOutcome = calculateTradeOutcome(
                                          userBalanceBefore.srcBalance,
                                          userBalanceBefore.destBalance,
                                          src,
                                          dest,
                                          destAddress
                                      );
                              
                                      require(reportedDestAmount == tradeOutcome.userDeltaDestAmount);
                                      require(tradeOutcome.userDeltaDestAmount <= maxDestAmount);
                                      require(tradeOutcome.actualRate >= minConversionRate);
                              
                                      ExecuteTrade(msg.sender, src, dest, tradeOutcome.userDeltaSrcAmount, tradeOutcome.userDeltaDestAmount);
                                      return tradeOutcome.userDeltaDestAmount;
                                  }
                              
                                  event KyberNetworkSet(address newNetworkContract, address oldNetworkContract);
                              
                                  function setKyberNetworkContract(KyberNetworkInterface _kyberNetworkContract) public onlyAdmin {
                              
                                      require(_kyberNetworkContract != address(0));
                              
                                      KyberNetworkSet(_kyberNetworkContract, kyberNetworkContract);
                              
                                      kyberNetworkContract = _kyberNetworkContract;
                                  }
                              
                                  function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty)
                                      public view
                                      returns(uint expectedRate, uint slippageRate)
                                  {
                                      return kyberNetworkContract.getExpectedRate(src, dest, srcQty);
                                  }
                              
                                  function getUserCapInWei(address user) public view returns(uint) {
                                      return kyberNetworkContract.getUserCapInWei(user);
                                  }
                              
                                  function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint) {
                                      return kyberNetworkContract.getUserCapInTokenWei(user, token);
                                  }
                              
                                  function maxGasPrice() public view returns(uint) {
                                      return kyberNetworkContract.maxGasPrice();
                                  }
                              
                                  function enabled() public view returns(bool) {
                                      return kyberNetworkContract.enabled();
                                  }
                              
                                  function info(bytes32 field) public view returns(uint) {
                                      return kyberNetworkContract.info(field);
                                  }
                              
                                  struct TradeOutcome {
                                      uint userDeltaSrcAmount;
                                      uint userDeltaDestAmount;
                                      uint actualRate;
                                  }
                              
                                  function calculateTradeOutcome (uint srcBalanceBefore, uint destBalanceBefore, ERC20 src, ERC20 dest,
                                      address destAddress)
                                      internal returns(TradeOutcome outcome)
                                  {
                                      uint userSrcBalanceAfter;
                                      uint userDestBalanceAfter;
                              
                                      userSrcBalanceAfter = getBalance(src, msg.sender);
                                      userDestBalanceAfter = getBalance(dest, destAddress);
                              
                                      //protect from underflow
                                      require(userDestBalanceAfter > destBalanceBefore);
                                      require(srcBalanceBefore > userSrcBalanceAfter);
                              
                                      outcome.userDeltaDestAmount = userDestBalanceAfter - destBalanceBefore;
                                      outcome.userDeltaSrcAmount = srcBalanceBefore - userSrcBalanceAfter;
                              
                                      outcome.actualRate = calcRateFromQty(
                                              outcome.userDeltaSrcAmount,
                                              outcome.userDeltaDestAmount,
                                              getDecimalsSafe(src),
                                              getDecimalsSafe(dest)
                                          );
                                  }
                              }

                              File 6 of 20: BancorNetwork
                              pragma solidity 0.4.26;
                              
                              // File: contracts/token/interfaces/IERC20Token.sol
                              
                              /*
                                  ERC20 Standard Token interface
                              */
                              contract IERC20Token {
                                  // these functions aren't abstract since the compiler emits automatically generated getter functions as external
                                  function name() public view returns (string) {}
                                  function symbol() public view returns (string) {}
                                  function decimals() public view returns (uint8) {}
                                  function totalSupply() public view returns (uint256) {}
                                  function balanceOf(address _owner) public view returns (uint256) { _owner; }
                                  function allowance(address _owner, address _spender) public view 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);
                              }
                              
                              // File: contracts/IBancorNetwork.sol
                              
                              /*
                                  Bancor Network interface
                              */
                              contract IBancorNetwork {
                                  function convert2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public payable returns (uint256);
                              
                                  function claimAndConvert2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public returns (uint256);
                              
                                  function convertFor2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public payable returns (uint256);
                              
                                  function claimAndConvertFor2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public returns (uint256);
                              
                                  function convertForPrioritized4(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256[] memory _signature,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convert(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function claimAndConvert(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn
                                  ) public returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convertFor(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function claimAndConvertFor(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for
                                  ) public returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convertForPrioritized3(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _customVal,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convertForPrioritized2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convertForPrioritized(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _block,
                                      uint256 _nonce,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  ) public payable returns (uint256);
                              }
                              
                              // File: contracts/ContractIds.sol
                              
                              /**
                                * @dev Id definitions for bancor contracts
                                * 
                                * Can be used in conjunction with the contract registry to get contract addresses
                              */
                              contract ContractIds {
                                  // generic
                                  bytes32 public constant CONTRACT_FEATURES = "ContractFeatures";
                                  bytes32 public constant CONTRACT_REGISTRY = "ContractRegistry";
                                  bytes32 public constant NON_STANDARD_TOKEN_REGISTRY = "NonStandardTokenRegistry";
                              
                                  // bancor logic
                                  bytes32 public constant BANCOR_NETWORK = "BancorNetwork";
                                  bytes32 public constant BANCOR_FORMULA = "BancorFormula";
                                  bytes32 public constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit";
                                  bytes32 public constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader";
                                  bytes32 public constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory";
                              
                                  // BNT core
                                  bytes32 public constant BNT_TOKEN = "BNTToken";
                                  bytes32 public constant BNT_CONVERTER = "BNTConverter";
                              
                                  // BancorX
                                  bytes32 public constant BANCOR_X = "BancorX";
                                  bytes32 public constant BANCOR_X_UPGRADER = "BancorXUpgrader";
                              }
                              
                              // File: contracts/FeatureIds.sol
                              
                              /**
                                * @dev Id definitions for bancor contract features
                                * 
                                * Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract
                              */
                              contract FeatureIds {
                                  // converter features
                                  uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0;
                              }
                              
                              // File: contracts/utility/interfaces/IWhitelist.sol
                              
                              /*
                                  Whitelist interface
                              */
                              contract IWhitelist {
                                  function isWhitelisted(address _address) public view returns (bool);
                              }
                              
                              // File: contracts/converter/interfaces/IBancorConverter.sol
                              
                              /*
                                  Bancor Converter interface
                              */
                              contract IBancorConverter {
                                  function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256);
                                  function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256);
                                  function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256);
                                  function conversionWhitelist() public view returns (IWhitelist) {}
                                  function conversionFee() public view returns (uint32) {}
                                  function reserves(address _address) public view returns (uint256, uint32, bool, bool, bool) { _address; }
                                  function getReserveBalance(IERC20Token _reserveToken) public view returns (uint256);
                                  // deprecated, backward compatibility
                                  function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
                                  function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
                                  function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
                                  function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool);
                                  function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256);
                              }
                              
                              // File: contracts/converter/interfaces/IBancorFormula.sol
                              
                              /*
                                  Bancor Formula interface
                              */
                              contract IBancorFormula {
                                  function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256);
                                  function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256);
                                  function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256);
                                  // deprecated, backward compatibility
                                  function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
                              }
                              
                              // File: contracts/converter/interfaces/IBancorGasPriceLimit.sol
                              
                              /*
                                  Bancor Gas Price Limit interface
                              */
                              contract IBancorGasPriceLimit {
                                  function gasPrice() public view returns (uint256) {}
                                  function validateGasPrice(uint256) public view;
                              }
                              
                              // File: contracts/utility/interfaces/IOwned.sol
                              
                              /*
                                  Owned contract interface
                              */
                              contract IOwned {
                                  // this function isn't abstract since the compiler emits automatically generated getter functions as external
                                  function owner() public view returns (address) {}
                              
                                  function transferOwnership(address _newOwner) public;
                                  function acceptOwnership() public;
                              }
                              
                              // File: contracts/utility/Owned.sol
                              
                              /**
                                * @dev Provides support and utilities for contract ownership
                              */
                              contract Owned is IOwned {
                                  address public owner;
                                  address public newOwner;
                              
                                  /**
                                    * @dev triggered when the owner is updated
                                    * 
                                    * @param _prevOwner previous owner
                                    * @param _newOwner  new owner
                                  */
                                  event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
                              
                                  /**
                                    * @dev initializes a new Owned instance
                                  */
                                  constructor() public {
                                      owner = msg.sender;
                                  }
                              
                                  // allows execution by the owner only
                                  modifier ownerOnly {
                                      require(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);
                                      emit OwnerUpdate(owner, newOwner);
                                      owner = newOwner;
                                      newOwner = address(0);
                                  }
                              }
                              
                              // File: contracts/utility/Utils.sol
                              
                              /**
                                * @dev Utilities & Common Modifiers
                              */
                              contract Utils {
                                  /**
                                    * constructor
                                  */
                                  constructor() public {
                                  }
                              
                                  // 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 != address(0));
                                      _;
                                  }
                              
                                  // verifies that the address is different than this contract address
                                  modifier notThis(address _address) {
                                      require(_address != address(this));
                                      _;
                                  }
                              
                              }
                              
                              // File: contracts/utility/interfaces/ITokenHolder.sol
                              
                              /*
                                  Token Holder interface
                              */
                              contract ITokenHolder is IOwned {
                                  function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
                              }
                              
                              // File: contracts/token/interfaces/INonStandardERC20.sol
                              
                              /*
                                  ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve
                              */
                              contract INonStandardERC20 {
                                  // these functions aren't abstract since the compiler emits automatically generated getter functions as external
                                  function name() public view returns (string) {}
                                  function symbol() public view returns (string) {}
                                  function decimals() public view returns (uint8) {}
                                  function totalSupply() public view returns (uint256) {}
                                  function balanceOf(address _owner) public view returns (uint256) { _owner; }
                                  function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
                              
                                  function transfer(address _to, uint256 _value) public;
                                  function transferFrom(address _from, address _to, uint256 _value) public;
                                  function approve(address _spender, uint256 _value) public;
                              }
                              
                              // File: contracts/utility/TokenHolder.sol
                              
                              /**
                                * @dev 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.
                                * 
                                * Note that we use the non standard ERC-20 interface which has no return value for transfer
                                * in order to support both non standard as well as standard token contracts.
                                * see https://github.com/ethereum/solidity/issues/4116
                              */
                              contract TokenHolder is ITokenHolder, Owned, Utils {
                                  /**
                                    * @dev initializes a new TokenHolder instance
                                  */
                                  constructor() public {
                                  }
                              
                                  /**
                                    * @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)
                                  {
                                      INonStandardERC20(_token).transfer(_to, _amount);
                                  }
                              }
                              
                              // File: contracts/utility/SafeMath.sol
                              
                              /**
                                * @dev Library for basic math operations with overflow/underflow protection
                              */
                              library SafeMath {
                                  /**
                                    * @dev returns the sum of _x and _y, reverts if the calculation overflows
                                    * 
                                    * @param _x   value 1
                                    * @param _y   value 2
                                    * 
                                    * @return sum
                                  */
                                  function add(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      uint256 z = _x + _y;
                                      require(z >= _x);
                                      return z;
                                  }
                              
                                  /**
                                    * @dev returns the difference of _x minus _y, reverts if the calculation underflows
                                    * 
                                    * @param _x   minuend
                                    * @param _y   subtrahend
                                    * 
                                    * @return difference
                                  */
                                  function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      require(_x >= _y);
                                      return _x - _y;
                                  }
                              
                                  /**
                                    * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows
                                    * 
                                    * @param _x   factor 1
                                    * @param _y   factor 2
                                    * 
                                    * @return product
                                  */
                                  function mul(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      // gas optimization
                                      if (_x == 0)
                                          return 0;
                              
                                      uint256 z = _x * _y;
                                      require(z / _x == _y);
                                      return z;
                                  }
                              
                                    /**
                                      * ev Integer division of two numbers truncating the quotient, reverts on division by zero.
                                      * 
                                      * aram _x   dividend
                                      * aram _y   divisor
                                      * 
                                      * eturn quotient
                                  */
                                  function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      require(_y > 0);
                                      uint256 c = _x / _y;
                              
                                      return c;
                                  }
                              }
                              
                              // File: contracts/utility/interfaces/IContractRegistry.sol
                              
                              /*
                                  Contract Registry interface
                              */
                              contract IContractRegistry {
                                  function addressOf(bytes32 _contractName) public view returns (address);
                              
                                  // deprecated, backward compatibility
                                  function getAddress(bytes32 _contractName) public view returns (address);
                              }
                              
                              // File: contracts/utility/interfaces/IContractFeatures.sol
                              
                              /*
                                  Contract Features interface
                              */
                              contract IContractFeatures {
                                  function isSupported(address _contract, uint256 _features) public view returns (bool);
                                  function enableFeatures(uint256 _features, bool _enable) public;
                              }
                              
                              // File: contracts/utility/interfaces/IAddressList.sol
                              
                              /*
                                  Address list interface
                              */
                              contract IAddressList {
                                  mapping (address => bool) public listedAddresses;
                              }
                              
                              // File: contracts/token/interfaces/IEtherToken.sol
                              
                              /*
                                  Ether Token interface
                              */
                              contract IEtherToken is ITokenHolder, IERC20Token {
                                  function deposit() public payable;
                                  function withdraw(uint256 _amount) public;
                                  function withdrawTo(address _to, uint256 _amount) public;
                              }
                              
                              // File: contracts/token/interfaces/ISmartToken.sol
                              
                              /*
                                  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;
                              }
                              
                              // File: contracts/bancorx/interfaces/IBancorX.sol
                              
                              contract IBancorX {
                                  function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) public;
                                  function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256);
                              }
                              
                              // File: contracts/BancorNetwork.sol
                              
                              /**
                                * @dev The BancorNetwork contract is the main entry point for Bancor token conversions. It also allows for the conversion of any token in the Bancor Network to any other token in a single transaction by providing a conversion path. 
                                * 
                                * A note on Conversion Path: Conversion path is a data structure that is used when converting a token to another token in the Bancor Network when the conversion cannot necessarily be done by a single converter and might require multiple 'hops'. The path defines which converters should be used and what kind of conversion should be done in each step. 
                                * 
                                * The path format doesn't include complex structure; instead, it is represented by a single array in which each 'hop' is represented by a 2-tuple - smart token & to token. In addition, the first element is always the source token. The smart token is only used as a pointer to a converter (since converter addresses are more likely to change as opposed to smart token addresses).
                                * 
                                * Format:
                                * [source token, smart token, to token, smart token, to token...]
                              */
                              contract BancorNetwork is IBancorNetwork, TokenHolder, ContractIds, FeatureIds {
                                  using SafeMath for uint256;
                              
                                  uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000;
                                  uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000;
                              
                                  uint256 public maxAffiliateFee = 30000;     // maximum affiliate-fee
                                  address public signerAddress = 0x0;         // verified address that allows conversions with higher gas price
                                  IContractRegistry public registry;          // contract registry contract address
                              
                                  mapping (address => bool) public etherTokens;       // list of all supported ether tokens
                                  mapping (bytes32 => bool) public conversionHashes;  // list of conversion hashes, to prevent re-use of the same hash
                              
                                  /**
                                    * @dev initializes a new BancorNetwork instance
                                    * 
                                    * @param _registry    address of a contract registry contract
                                  */
                                  constructor(IContractRegistry _registry) public validAddress(_registry) {
                                      registry = _registry;
                                  }
                              
                                  /**
                                    * @dev allows the owner to update the maximum affiliate-fee
                                    * 
                                    * @param _maxAffiliateFee   maximum affiliate-fee
                                  */
                                  function setMaxAffiliateFee(uint256 _maxAffiliateFee)
                                      public
                                      ownerOnly
                                  {
                                      require(_maxAffiliateFee <= AFFILIATE_FEE_RESOLUTION);
                                      maxAffiliateFee = _maxAffiliateFee;
                                  }
                              
                                  /**
                                    * @dev allows the owner to update the contract registry contract address
                                    * 
                                    * @param _registry   address of a contract registry contract
                                  */
                                  function setRegistry(IContractRegistry _registry)
                                      public
                                      ownerOnly
                                      validAddress(_registry)
                                      notThis(_registry)
                                  {
                                      registry = _registry;
                                  }
                              
                                  /**
                                    * @dev allows the owner to update the signer address
                                    * 
                                    * @param _signerAddress    new signer address
                                  */
                                  function setSignerAddress(address _signerAddress)
                                      public
                                      ownerOnly
                                      validAddress(_signerAddress)
                                      notThis(_signerAddress)
                                  {
                                      signerAddress = _signerAddress;
                                  }
                              
                                  /**
                                    * @dev allows the owner to register/unregister ether tokens
                                    * 
                                    * @param _token       ether token contract address
                                    * @param _register    true to register, false to unregister
                                  */
                                  function registerEtherToken(IEtherToken _token, bool _register)
                                      public
                                      ownerOnly
                                      validAddress(_token)
                                      notThis(_token)
                                  {
                                      etherTokens[_token] = _register;
                                  }
                              
                                  /**
                                    * @dev verifies that the signer address is trusted by recovering 
                                    * the address associated with the public key from elliptic 
                                    * curve signature, returns zero on error.
                                    * notice that the signature is valid only for one conversion
                                    * and expires after the give block.
                                  */
                                  function verifyTrustedSender(IERC20Token[] _path, address _addr, uint256[] memory _signature) private {
                                      uint256 blockNumber = _signature[1];
                              
                                      // check that the current block number doesn't exceeded the maximum allowed with the current signature
                                      require(block.number <= blockNumber);
                              
                                      // create the hash of the given signature
                                      bytes32 hash = keccak256(abi.encodePacked(blockNumber, tx.gasprice, _addr, msg.sender, _signature[0], _path));
                              
                                      // check that it is the first conversion with the given signature
                                      require(!conversionHashes[hash]);
                              
                                      // verify that the signing address is identical to the trusted signer address in the contract
                                      bytes32 prefixedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
                                      require(ecrecover(prefixedHash, uint8(_signature[2]), bytes32(_signature[3]), bytes32(_signature[4])) == signerAddress);
                              
                                      // mark the hash so that it can't be used multiple times
                                      conversionHashes[hash] = true;
                                  }
                              
                                  /**
                                    * @dev converts the token to any other token in the bancor network by following
                                    * a predefined conversion path and transfers the result tokens to a target account
                                    * note that the converter should already own the source tokens
                                    * 
                                    * @param _path                conversion path, see conversion path format above
                                    * @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
                                    * @param _for                 account that will receive the conversion result
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return tokens issued in return
                                  */
                                  function convertFor2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) {
                                      return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(0x0, 0x0, 0x0, 0x0, 0x0), _affiliateAccount, _affiliateFee);
                                  }
                              
                                  /**
                                    * @dev converts the token to any other token in the bancor network
                                    * by following a predefined conversion path and transfers the result
                                    * tokens to a target account.
                                    * this version of the function also allows the verified signer
                                    * to bypass the universal gas price limit.
                                    * note that the converter should already own the source tokens
                                    * 
                                    * @param _path                conversion path, see conversion path format above
                                    * @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
                                    * @param _for                 account that will receive the conversion result
                                    * @param _signature           an array of the following elements:
                                    *                             [0] uint256     custom value that was signed for prioritized conversion
                                    *                             [1] uint256     if the current block exceeded the given parameter - it is cancelled
                                    *                             [2] uint8       (signature[128:130]) associated with the signer address and helps to validate if the signature is legit
                                    *                             [3] bytes32     (signature[0:64]) associated with the signer address and helps to validate if the signature is legit
                                    *                             [4] bytes32     (signature[64:128]) associated with the signer address and helps to validate if the signature is legit
                                    *                             if the array is empty (length == 0), then the gas-price limit is verified instead of the signature
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return tokens issued in return
                                  */
                                  function convertForPrioritized4(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256[] memory _signature,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  )
                                      public
                                      payable
                                      returns (uint256)
                                  {
                                      // verify that the conversion parameters are legal
                                      verifyConversionParams(_path, _for, _for, _signature);
                              
                                      // handle msg.value
                                      handleValue(_path[0], _amount, false);
                              
                                      // convert and get the resulting amount
                                      uint256 amount = convertByPath(_path, _amount, _minReturn, _affiliateAccount, _affiliateFee);
                              
                                      // finished the conversion, transfer the funds to the target account
                                      // if the target token is an ether token, withdraw the tokens and send them as ETH
                                      // otherwise, transfer the tokens as is
                                      IERC20Token toToken = _path[_path.length - 1];
                                      if (etherTokens[toToken])
                                          IEtherToken(toToken).withdrawTo(_for, amount);
                                      else
                                          ensureTransfer(toToken, _for, amount);
                              
                                      return amount;
                                  }
                              
                                  /**
                                    * @dev converts any other token to BNT in the bancor network
                                    * by following a predefined conversion path and transfers the resulting
                                    * tokens to BancorX.
                                    * note that the network should already have been given allowance of the source token (if not ETH)
                                    * 
                                    * @param _path             conversion path, see conversion path format above
                                    * @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
                                    * @param _toBlockchain     blockchain BNT will be issued on
                                    * @param _to               address/account on _toBlockchain to send the BNT to
                                    * @param _conversionId     pre-determined unique (if non zero) id which refers to this transaction 
                                    * 
                                    * @return the amount of BNT received from this conversion
                                  */
                                  function xConvert(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      bytes32 _toBlockchain,
                                      bytes32 _to,
                                      uint256 _conversionId
                                  )
                                      public
                                      payable
                                      returns (uint256)
                                  {
                                      return xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, getSignature(0x0, 0x0, 0x0, 0x0, 0x0));
                                  }
                              
                                  /**
                                    * @dev converts any other token to BNT in the bancor network
                                    * by following a predefined conversion path and transfers the resulting
                                    * tokens to BancorX.
                                    * this version of the function also allows the verified signer
                                    * to bypass the universal gas price limit.
                                    * note that the network should already have been given allowance of the source token (if not ETH)
                                    * 
                                    * @param _path            conversion path, see conversion path format above
                                    * @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
                                    * @param _toBlockchain    blockchain BNT will be issued on
                                    * @param _to              address/account on _toBlockchain to send the BNT to
                                    * @param _conversionId    pre-determined unique (if non zero) id which refers to this transaction 
                                    * @param _signature       an array of the following elements:
                                    *                         [0] uint256     custom value that was signed for prioritized conversion; must be equal to _amount
                                    *                         [1] uint256     if the current block exceeded the given parameter - it is cancelled
                                    *                         [2] uint8       (signature[128:130]) associated with the signer address and helps to validate if the signature is legit
                                    *                         [3] bytes32     (signature[0:64]) associated with the signer address and helps to validate if the signature is legit
                                    *                         [4] bytes32     (signature[64:128]) associated with the signer address and helps to validate if the signature is legit
                                    *                         if the array is empty (length == 0), then the gas-price limit is verified instead of the signature
                                    * 
                                    * @return the amount of BNT received from this conversion
                                  */
                                  function xConvertPrioritized2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      bytes32 _toBlockchain,
                                      bytes32 _to,
                                      uint256 _conversionId,
                                      uint256[] memory _signature
                                  )
                                      public
                                      payable
                                      returns (uint256)
                                  {
                                      // verify that the custom value (if valid) is equal to _amount
                                      require(_signature.length == 0 || _signature[0] == _amount);
                              
                                      // verify that the conversion parameters are legal
                                      verifyConversionParams(_path, msg.sender, this, _signature);
                              
                                      // verify that the destination token is BNT
                                      require(_path[_path.length - 1] == registry.addressOf(ContractIds.BNT_TOKEN));
                              
                                      // handle msg.value
                                      handleValue(_path[0], _amount, true);
                              
                                      // convert and get the resulting amount
                                      uint256 amount = convertByPath(_path, _amount, _minReturn, address(0), 0);
                              
                                      // transfer the resulting amount to BancorX
                                      IBancorX(registry.addressOf(ContractIds.BANCOR_X)).xTransfer(_toBlockchain, _to, amount, _conversionId);
                              
                                      return amount;
                                  }
                              
                                  /**
                                    * @dev executes the actual conversion by following the conversion path
                                    * 
                                    * @param _path                conversion path, see conversion path format above
                                    * @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
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return amount of tokens issued
                                  */
                                  function convertByPath(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) private returns (uint256) {
                                      uint256 amount = _amount;
                                      uint256 lastIndex = _path.length - 1;
                              
                                      address bntToken;
                                      if (address(_affiliateAccount) == 0) {
                                          require(_affiliateFee == 0);
                                          bntToken = address(0);
                                      }
                                      else {
                                          require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee);
                                          bntToken = registry.addressOf(ContractIds.BNT_TOKEN);
                                      }
                              
                                      // iterate over the conversion path
                                      for (uint256 i = 2; i <= lastIndex; i += 2) {
                                          IBancorConverter converter = IBancorConverter(ISmartToken(_path[i - 1]).owner());
                              
                                          // if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request
                                          if (_path[i - 1] != _path[i - 2])
                                              ensureAllowance(_path[i - 2], converter, amount);
                              
                                          // make the conversion - if it's the last one, also provide the minimum return value
                                          amount = converter.change(_path[i - 2], _path[i], amount, i == lastIndex ? _minReturn : 1);
                              
                                          // pay affiliate-fee if needed
                                          if (address(_path[i]) == bntToken) {
                                              uint256 affiliateAmount = amount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION);
                                              require(_path[i].transfer(_affiliateAccount, affiliateAmount));
                                              amount -= affiliateAmount;
                                              bntToken = address(0);
                                          }
                                      }
                              
                                      return amount;
                                  }
                              
                                  bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(uint256(keccak256("getReturn(address,address,uint256)") >> (256 - 4 * 8)));
                              
                                  function getReturn(address _dest, address _fromToken, address _toToken, uint256 _amount) internal view returns (uint256, uint256) {
                                      uint256[2] memory ret;
                                      bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _fromToken, _toToken, _amount);
                              
                                      assembly {
                                          let success := staticcall(
                                              gas,           // gas remaining
                                              _dest,         // destination address
                                              add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array)
                                              mload(data),   // input length (loaded from the first 32 bytes in the `data` array)
                                              ret,           // output buffer
                                              64             // output length
                                          )
                                          if iszero(success) {
                                              revert(0, 0)
                                          }
                                      }
                              
                                      return (ret[0], ret[1]);
                                  }
                              
                                  /**
                                    * @dev returns the expected return amount for converting a specific amount by following
                                    * a given conversion path.
                                    * notice that there is no support for circular paths.
                                    * 
                                    * @param _path        conversion path, see conversion path format above
                                    * @param _amount      amount to convert from (in the initial source token)
                                    * 
                                    * @return expected conversion return amount and conversion fee
                                  */
                                  function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) {
                                      uint256 amount;
                                      uint256 fee;
                                      uint256 supply;
                                      uint256 balance;
                                      uint32 ratio;
                                      IBancorConverter converter;
                                      IBancorFormula formula = IBancorFormula(registry.addressOf(ContractIds.BANCOR_FORMULA));
                              
                                      amount = _amount;
                              
                                      // verify that the number of elements is larger than 2 and odd
                                      require(_path.length > 2 && _path.length % 2 == 1);
                              
                                      // iterate over the conversion path
                                      for (uint256 i = 2; i < _path.length; i += 2) {
                                          IERC20Token fromToken = _path[i - 2];
                                          IERC20Token smartToken = _path[i - 1];
                                          IERC20Token toToken = _path[i];
                              
                                          if (toToken == smartToken) { // buy the smart token
                                              // check if the current smart token has changed
                                              if (i < 3 || smartToken != _path[i - 3]) {
                                                  supply = smartToken.totalSupply();
                                                  converter = IBancorConverter(ISmartToken(smartToken).owner());
                                              }
                              
                                              // validate input
                                              require(getReserveSaleEnabled(converter, fromToken));
                              
                                              // calculate the amount & the conversion fee
                                              balance = converter.getConnectorBalance(fromToken);
                                              (, ratio, , , ) = converter.connectors(fromToken);
                                              amount = formula.calculatePurchaseReturn(supply, balance, ratio, amount);
                                              fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION);
                                              amount -= fee;
                              
                                              // update the smart token supply for the next iteration
                                              supply += amount;
                                          }
                                          else if (fromToken == smartToken) { // sell the smart token
                                              // check if the current smart token has changed
                                              if (i < 3 || smartToken != _path[i - 3]) {
                                                  supply = smartToken.totalSupply();
                                                  converter = IBancorConverter(ISmartToken(smartToken).owner());
                                              }
                              
                                              // calculate the amount & the conversion fee
                                              balance = converter.getConnectorBalance(toToken);
                                              (, ratio, , , ) = converter.connectors(toToken);
                                              amount = formula.calculateSaleReturn(supply, balance, ratio, amount);
                                              fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION);
                                              amount -= fee;
                              
                                              // update the smart token supply for the next iteration
                                              supply -= amount;
                                          }
                                          else { // cross reserve conversion
                                              // check if the current smart token has changed
                                              if (i < 3 || smartToken != _path[i - 3]) {
                                                  converter = IBancorConverter(ISmartToken(smartToken).owner());
                                              }
                              
                                              (amount, fee) = getReturn(converter, fromToken, toToken, amount);
                                          }
                                      }
                              
                                      return (amount, fee);
                                  }
                              
                                  /**
                                    * @dev claims the caller's tokens, converts them to any other token in the bancor network
                                    * by following a predefined conversion path and transfers the result tokens to a target account
                                    * note that allowance must be set beforehand
                                    * 
                                    * @param _path                conversion path, see conversion path format above
                                    * @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
                                    * @param _for                 account that will receive the conversion result
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return tokens issued in return
                                  */
                                  function claimAndConvertFor2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) {
                                      // we need to transfer the tokens from the caller to the converter before we follow
                                      // the conversion path, to allow it to execute the conversion on behalf of the caller
                                      // note: we assume we already have allowance
                                      IERC20Token fromToken = _path[0];
                                      ensureTransferFrom(fromToken, msg.sender, this, _amount);
                                      return convertFor2(_path, _amount, _minReturn, _for, _affiliateAccount, _affiliateFee);
                                  }
                              
                                  /**
                                    * @dev converts the token to any other token in the bancor network by following
                                    * a predefined conversion path and transfers the result tokens back to the sender
                                    * note that the converter should already own the source tokens
                                    * 
                                    * @param _path                conversion path, see conversion path format above
                                    * @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
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return tokens issued in return
                                  */
                                  function convert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) {
                                      return convertFor2(_path, _amount, _minReturn, msg.sender, _affiliateAccount, _affiliateFee);
                                  }
                              
                                  /**
                                    * @dev claims the caller's tokens, converts them to any other token in the bancor network
                                    * by following a predefined conversion path and transfers the result tokens back to the sender
                                    * note that allowance must be set beforehand
                                    * 
                                    * @param _path                conversion path, see conversion path format above
                                    * @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
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return tokens issued in return
                                  */
                                  function claimAndConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) {
                                      return claimAndConvertFor2(_path, _amount, _minReturn, msg.sender, _affiliateAccount, _affiliateFee);
                                  }
                              
                                  /**
                                    * @dev ensures transfer of tokens, taking into account that some ERC-20 implementations don't return
                                    * true on success but revert on failure instead
                                    * 
                                    * @param _token     the token to transfer
                                    * @param _to        the address to transfer the tokens to
                                    * @param _amount    the amount to transfer
                                  */
                                  function ensureTransfer(IERC20Token _token, address _to, uint256 _amount) private {
                                      IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY));
                              
                                      if (addressList.listedAddresses(_token)) {
                                          uint256 prevBalance = _token.balanceOf(_to);
                                          // we have to cast the token contract in an interface which has no return value
                                          INonStandardERC20(_token).transfer(_to, _amount);
                                          uint256 postBalance = _token.balanceOf(_to);
                                          assert(postBalance > prevBalance);
                                      } else {
                                          // if the token isn't whitelisted, we assert on transfer
                                          assert(_token.transfer(_to, _amount));
                                      }
                                  }
                              
                                  /**
                                    * @dev ensures transfer of tokens, taking into account that some ERC-20 implementations don't return
                                    * true on success but revert on failure instead
                                    * 
                                    * @param _token     the token to transfer
                                    * @param _from      the address to transfer the tokens from
                                    * @param _to        the address to transfer the tokens to
                                    * @param _amount    the amount to transfer
                                  */
                                  function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private {
                                      IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY));
                              
                                      if (addressList.listedAddresses(_token)) {
                                          uint256 prevBalance = _token.balanceOf(_to);
                                          // we have to cast the token contract in an interface which has no return value
                                          INonStandardERC20(_token).transferFrom(_from, _to, _amount);
                                          uint256 postBalance = _token.balanceOf(_to);
                                          assert(postBalance > prevBalance);
                                      } else {
                                          // if the token isn't whitelisted, we assert on transfer
                                          assert(_token.transferFrom(_from, _to, _amount));
                                      }
                                  }
                              
                                  /**
                                    * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't.
                                    * Note that we use the non standard erc-20 interface in which `approve` has no return value so that
                                    * this function will work for both standard and non standard tokens
                                    * 
                                    * @param _token   token to check the allowance in
                                    * @param _spender approved address
                                    * @param _value   allowance amount
                                  */
                                  function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private {
                                      // check if allowance for the given amount already exists
                                      if (_token.allowance(this, _spender) >= _value)
                                          return;
                              
                                      // if the allowance is nonzero, must reset it to 0 first
                                      if (_token.allowance(this, _spender) != 0)
                                          INonStandardERC20(_token).approve(_spender, 0);
                              
                                      // approve the new allowance
                                      INonStandardERC20(_token).approve(_spender, _value);
                                  }
                              
                                  /**
                                    * @dev returns true if reserve sale is enabled
                                    * 
                                    * @param _converter       converter contract address
                                    * @param _reserve         reserve's address to read from
                                    * 
                                    * @return true if reserve sale is enabled, otherwise - false
                                  */
                                  function getReserveSaleEnabled(IBancorConverter _converter, IERC20Token _reserve)
                                      private
                                      view
                                      returns(bool)
                                  {
                                      bool isSaleEnabled;
                                      (, , , isSaleEnabled, ) = _converter.connectors(_reserve);
                                      return isSaleEnabled;
                                  }
                              
                                  function getSignature(
                                      uint256 _customVal,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  ) private pure returns (uint256[] memory) {
                                      if (_v == 0x0 && _r == 0x0 && _s == 0x0)
                                          return new uint256[](0);
                                      uint256[] memory signature = new uint256[](5);
                                      signature[0] = _customVal;
                                      signature[1] = _block;
                                      signature[2] = uint256(_v);
                                      signature[3] = uint256(_r);
                                      signature[4] = uint256(_s);
                                      return signature;
                                  }
                              
                                  function verifyConversionParams(
                                      IERC20Token[] _path,
                                      address _sender,
                                      address _receiver,
                                      uint256[] memory _signature
                                  )
                                      private
                                  {
                                      // verify that the number of elements is odd and that maximum number of 'hops' is 10
                                      require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
                              
                                      // verify that the account which should receive the conversion result is whitelisted
                                      IContractFeatures features = IContractFeatures(registry.addressOf(ContractIds.CONTRACT_FEATURES));
                                      for (uint256 i = 1; i < _path.length; i += 2) {
                                          IBancorConverter converter = IBancorConverter(ISmartToken(_path[i]).owner());
                                          if (features.isSupported(converter, FeatureIds.CONVERTER_CONVERSION_WHITELIST)) {
                                              IWhitelist whitelist = converter.conversionWhitelist();
                                              require (whitelist == address(0) || whitelist.isWhitelisted(_receiver));
                                          }
                                      }
                              
                                      if (_signature.length >= 5) {
                                          // verify signature
                                          verifyTrustedSender(_path, _sender, _signature);
                                      }
                                      else {
                                          // verify gas price limit
                                          IBancorGasPriceLimit gasPriceLimit = IBancorGasPriceLimit(registry.addressOf(ContractIds.BANCOR_GAS_PRICE_LIMIT));
                                          gasPriceLimit.validateGasPrice(tx.gasprice);
                                      }
                                  }
                              
                                  function handleValue(IERC20Token _token, uint256 _amount, bool _claim) private {
                                      // if ETH is provided, ensure that the amount is identical to _amount, verify that the source token is an ether token and deposit the ETH in it
                                      if (msg.value > 0) {
                                          require(_amount == msg.value && etherTokens[_token]);
                                          IEtherToken(_token).deposit.value(msg.value)();
                                      }
                                      // Otherwise, claim the tokens from the sender if needed
                                      else if (_claim) {
                                          ensureTransferFrom(_token, msg.sender, this, _amount);
                                      }
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function convert(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn
                                  ) public payable returns (uint256)
                                  {
                                      return convert2(_path, _amount, _minReturn, address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function claimAndConvert(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn
                                  ) public returns (uint256)
                                  {
                                      return claimAndConvert2(_path, _amount, _minReturn, address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function convertFor(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for
                                  ) public payable returns (uint256)
                                  {
                                      return convertFor2(_path, _amount, _minReturn, _for, address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function claimAndConvertFor(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for
                                  ) public returns (uint256)
                                  {
                                      return claimAndConvertFor2(_path, _amount, _minReturn, _for, address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function xConvertPrioritized(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      bytes32 _toBlockchain,
                                      bytes32 _to,
                                      uint256 _conversionId,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  )
                                      public
                                      payable
                                      returns (uint256)
                                  {
                                      // workaround the 'stack too deep' compilation error
                                      uint256[] memory signature = getSignature(_amount, _block, _v, _r, _s);
                                      return xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, signature);
                                      // return xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, getSignature(_amount, _block, _v, _r, _s));
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function convertForPrioritized3(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _customVal,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  )
                                      public
                                      payable
                                      returns (uint256)
                                  {
                                      return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_customVal, _block, _v, _r, _s), address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function convertForPrioritized2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  )
                                      public
                                      payable
                                      returns (uint256)
                                  {
                                      return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_amount, _block, _v, _r, _s), address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function convertForPrioritized(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _block,
                                      uint256 _nonce,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s)
                                      public payable returns (uint256)
                                  {
                                      _nonce;
                                      return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_amount, _block, _v, _r, _s), address(0), 0);
                                  }
                              }
                              

                              File 7 of 20: 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 8 of 20: SmartToken
                              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;
                                  }
                              }
                              
                              /*
                                  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);
                              }
                              
                              /**
                                  ERC20 Standard Token implementation
                              */
                              contract ERC20Token is IERC20Token, Utils {
                                  string public standard = 'Token 0.1';
                                  string public name = '';
                                  string public symbol = '';
                                  uint8 public decimals = 0;
                                  uint256 public totalSupply = 0;
                                  mapping (address => uint256) public balanceOf;
                                  mapping (address => mapping (address => uint256)) public allowance;
                              
                                  event Transfer(address indexed _from, address indexed _to, uint256 _value);
                                  event Approval(address indexed _owner, address indexed _spender, uint256 _value);
                              
                                  /**
                                      @dev constructor
                              
                                      @param _name        token name
                                      @param _symbol      token symbol
                                      @param _decimals    decimal points, for display purposes
                                  */
                                  function ERC20Token(string _name, string _symbol, uint8 _decimals) {
                                      require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
                              
                                      name = _name;
                                      symbol = _symbol;
                                      decimals = _decimals;
                                  }
                              
                                  /**
                                      @dev send coins
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transfer(address _to, uint256 _value)
                                      public
                                      validAddress(_to)
                                      returns (bool success)
                                  {
                                      balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
                                      balanceOf[_to] = safeAdd(balanceOf[_to], _value);
                                      Transfer(msg.sender, _to, _value);
                                      return true;
                                  }
                              
                                  /**
                                      @dev an account/contract attempts to get the coins
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      @param _from    source address
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transferFrom(address _from, address _to, uint256 _value)
                                      public
                                      validAddress(_from)
                                      validAddress(_to)
                                      returns (bool success)
                                  {
                                      allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
                                      balanceOf[_from] = safeSub(balanceOf[_from], _value);
                                      balanceOf[_to] = safeAdd(balanceOf[_to], _value);
                                      Transfer(_from, _to, _value);
                                      return true;
                                  }
                              
                                  /**
                                      @dev allow another account/contract to spend some tokens on your behalf
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      also, to minimize the risk of the approve/transferFrom attack vector
                                      (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
                                      in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
                              
                                      @param _spender approved address
                                      @param _value   allowance amount
                              
                                      @return true if the approval was successful, false if it wasn't
                                  */
                                  function approve(address _spender, uint256 _value)
                                      public
                                      validAddress(_spender)
                                      returns (bool success)
                                  {
                                      // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
                                      require(_value == 0 || allowance[msg.sender][_spender] == 0);
                              
                                      allowance[msg.sender][_spender] = _value;
                                      Approval(msg.sender, _spender, _value);
                                      return true;
                                  }
                              }
                              
                              /*
                                  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));
                                  }
                              }
                              
                              /*
                                  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;
                              }
                              
                              /*
                                  Smart Token v0.3
                              
                                  'Owned' is specified here for readability reasons
                              */
                              contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder {
                                  string public version = '0.3';
                              
                                  bool public transfersEnabled = true;    // true if transfer/transferFrom are enabled, false if not
                              
                                  // triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
                                  event NewSmartToken(address _token);
                                  // triggered when the total supply is increased
                                  event Issuance(uint256 _amount);
                                  // triggered when the total supply is decreased
                                  event Destruction(uint256 _amount);
                              
                                  /**
                                      @dev constructor
                              
                                      @param _name       token name
                                      @param _symbol     token short symbol, minimum 1 character
                                      @param _decimals   for display purposes only
                                  */
                                  function SmartToken(string _name, string _symbol, uint8 _decimals)
                                      ERC20Token(_name, _symbol, _decimals)
                                  {
                                      NewSmartToken(address(this));
                                  }
                              
                                  // allows execution only when transfers aren't disabled
                                  modifier transfersAllowed {
                                      assert(transfersEnabled);
                                      _;
                                  }
                              
                                  /**
                                      @dev disables/enables transfers
                                      can only be called by the contract owner
                              
                                      @param _disable    true to disable transfers, false to enable them
                                  */
                                  function disableTransfers(bool _disable) public ownerOnly {
                                      transfersEnabled = !_disable;
                                  }
                              
                                  /**
                                      @dev increases the token supply and sends the new tokens to an account
                                      can only be called by the contract owner
                              
                                      @param _to         account to receive the new amount
                                      @param _amount     amount to increase the supply by
                                  */
                                  function issue(address _to, uint256 _amount)
                                      public
                                      ownerOnly
                                      validAddress(_to)
                                      notThis(_to)
                                  {
                                      totalSupply = safeAdd(totalSupply, _amount);
                                      balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
                              
                                      Issuance(_amount);
                                      Transfer(this, _to, _amount);
                                  }
                              
                                  /**
                                      @dev removes tokens from an account and decreases the token supply
                                      can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
                              
                                      @param _from       account to remove the amount from
                                      @param _amount     amount to decrease the supply by
                                  */
                                  function destroy(address _from, uint256 _amount) public {
                                      require(msg.sender == _from || msg.sender == owner); // validate input
                              
                                      balanceOf[_from] = safeSub(balanceOf[_from], _amount);
                                      totalSupply = safeSub(totalSupply, _amount);
                              
                                      Transfer(_from, this, _amount);
                                      Destruction(_amount);
                                  }
                              
                                  // ERC20 standard method overrides with some extra functionality
                              
                                  /**
                                      @dev send coins
                                      throws on any error rather then return a false flag to minimize user errors
                                      in addition to the standard checks, the function throws if transfers are disabled
                              
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
                                      assert(super.transfer(_to, _value));
                                      return true;
                                  }
                              
                                  /**
                                      @dev an account/contract attempts to get the coins
                                      throws on any error rather then return a false flag to minimize user errors
                                      in addition to the standard checks, the function throws if transfers are disabled
                              
                                      @param _from    source address
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
                                      assert(super.transferFrom(_from, _to, _value));
                                      return true;
                                  }
                              }

                              File 9 of 20: SmartToken
                              pragma solidity ^0.4.11;
                              
                              /*
                                  Overflow protected math functions
                              */
                              contract SafeMath {
                                  /**
                                      constructor
                                  */
                                  function SafeMath() {
                                  }
                              
                                  /**
                                      @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 owner) { owner; }
                              
                                  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 need 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;
                                  }
                              }
                              
                              /*
                                  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 {
                                  /**
                                      @dev constructor
                                  */
                                  function TokenHolder() {
                                  }
                              
                                  // 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));
                                      _;
                                  }
                              
                                  /**
                                      @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));
                                  }
                              }
                              
                              /*
                                  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 name) { name; }
                                  function symbol() public constant returns (string symbol) { symbol; }
                                  function decimals() public constant returns (uint8 decimals) { decimals; }
                                  function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; }
                                  function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
                                  function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; }
                              
                                  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);
                              }
                              
                              /**
                                  ERC20 Standard Token implementation
                              */
                              contract ERC20Token is IERC20Token, SafeMath {
                                  string public standard = 'Token 0.1';
                                  string public name = '';
                                  string public symbol = '';
                                  uint8 public decimals = 0;
                                  uint256 public totalSupply = 0;
                                  mapping (address => uint256) public balanceOf;
                                  mapping (address => mapping (address => uint256)) public allowance;
                              
                                  event Transfer(address indexed _from, address indexed _to, uint256 _value);
                                  event Approval(address indexed _owner, address indexed _spender, uint256 _value);
                              
                                  /**
                                      @dev constructor
                              
                                      @param _name        token name
                                      @param _symbol      token symbol
                                      @param _decimals    decimal points, for display purposes
                                  */
                                  function ERC20Token(string _name, string _symbol, uint8 _decimals) {
                                      require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
                              
                                      name = _name;
                                      symbol = _symbol;
                                      decimals = _decimals;
                                  }
                              
                                  // validates an address - currently only checks that it isn't null
                                  modifier validAddress(address _address) {
                                      require(_address != 0x0);
                                      _;
                                  }
                              
                                  /**
                                      @dev send coins
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transfer(address _to, uint256 _value)
                                      public
                                      validAddress(_to)
                                      returns (bool success)
                                  {
                                      balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
                                      balanceOf[_to] = safeAdd(balanceOf[_to], _value);
                                      Transfer(msg.sender, _to, _value);
                                      return true;
                                  }
                              
                                  /**
                                      @dev an account/contract attempts to get the coins
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      @param _from    source address
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transferFrom(address _from, address _to, uint256 _value)
                                      public
                                      validAddress(_from)
                                      validAddress(_to)
                                      returns (bool success)
                                  {
                                      allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
                                      balanceOf[_from] = safeSub(balanceOf[_from], _value);
                                      balanceOf[_to] = safeAdd(balanceOf[_to], _value);
                                      Transfer(_from, _to, _value);
                                      return true;
                                  }
                              
                                  /**
                                      @dev allow another account/contract to spend some tokens on your behalf
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      also, to minimize the risk of the approve/transferFrom attack vector
                                      (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
                                      in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
                              
                                      @param _spender approved address
                                      @param _value   allowance amount
                              
                                      @return true if the approval was successful, false if it wasn't
                                  */
                                  function approve(address _spender, uint256 _value)
                                      public
                                      validAddress(_spender)
                                      returns (bool success)
                                  {
                                      // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
                                      require(_value == 0 || allowance[msg.sender][_spender] == 0);
                              
                                      allowance[msg.sender][_spender] = _value;
                                      Approval(msg.sender, _spender, _value);
                                      return true;
                                  }
                              }
                              
                              /*
                                  Smart Token interface
                              */
                              contract ISmartToken is ITokenHolder, IERC20Token {
                                  function disableTransfers(bool _disable) public;
                                  function issue(address _to, uint256 _amount) public;
                                  function destroy(address _from, uint256 _amount) public;
                              }
                              
                              /*
                                  Smart Token v0.2
                              
                                  'Owned' is specified here for readability reasons
                              */
                              contract SmartToken is ISmartToken, ERC20Token, Owned, TokenHolder {
                                  string public version = '0.2';
                              
                                  bool public transfersEnabled = true;    // true if transfer/transferFrom are enabled, false if not
                              
                                  // triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
                                  event NewSmartToken(address _token);
                                  // triggered when the total supply is increased
                                  event Issuance(uint256 _amount);
                                  // triggered when the total supply is decreased
                                  event Destruction(uint256 _amount);
                              
                                  /**
                                      @dev constructor
                              
                                      @param _name       token name
                                      @param _symbol     token short symbol, 1-6 characters
                                      @param _decimals   for display purposes only
                                  */
                                  function SmartToken(string _name, string _symbol, uint8 _decimals)
                                      ERC20Token(_name, _symbol, _decimals)
                                  {
                                      require(bytes(_symbol).length <= 6); // validate input
                                      NewSmartToken(address(this));
                                  }
                              
                                  // allows execution only when transfers aren't disabled
                                  modifier transfersAllowed {
                                      assert(transfersEnabled);
                                      _;
                                  }
                              
                                  /**
                                      @dev disables/enables transfers
                                      can only be called by the contract owner
                              
                                      @param _disable    true to disable transfers, false to enable them
                                  */
                                  function disableTransfers(bool _disable) public ownerOnly {
                                      transfersEnabled = !_disable;
                                  }
                              
                                  /**
                                      @dev increases the token supply and sends the new tokens to an account
                                      can only be called by the contract owner
                              
                                      @param _to         account to receive the new amount
                                      @param _amount     amount to increase the supply by
                                  */
                                  function issue(address _to, uint256 _amount)
                                      public
                                      ownerOnly
                                      validAddress(_to)
                                      notThis(_to)
                                  {
                                      totalSupply = safeAdd(totalSupply, _amount);
                                      balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
                              
                                      Issuance(_amount);
                                      Transfer(this, _to, _amount);
                                  }
                              
                                  /**
                                      @dev removes tokens from an account and decreases the token supply
                                      can only be called by the contract owner
                              
                                      @param _from       account to remove the amount from
                                      @param _amount     amount to decrease the supply by
                                  */
                                  function destroy(address _from, uint256 _amount)
                                      public
                                      ownerOnly
                                  {
                                      balanceOf[_from] = safeSub(balanceOf[_from], _amount);
                                      totalSupply = safeSub(totalSupply, _amount);
                              
                                      Transfer(_from, this, _amount);
                                      Destruction(_amount);
                                  }
                              
                                  // ERC20 standard method overrides with some extra functionality
                              
                                  /**
                                      @dev send coins
                                      throws on any error rather then return a false flag to minimize user errors
                                      note that when transferring to the smart token's address, the coins are actually destroyed
                              
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
                                      assert(super.transfer(_to, _value));
                              
                                      // transferring to the contract address destroys tokens
                                      if (_to == address(this)) {
                                          balanceOf[_to] -= _value;
                                          totalSupply -= _value;
                                          Destruction(_value);
                                      }
                              
                                      return true;
                                  }
                              
                                  /**
                                      @dev an account/contract attempts to get the coins
                                      throws on any error rather then return a false flag to minimize user errors
                                      note that when transferring to the smart token's address, the coins are actually destroyed
                              
                                      @param _from    source address
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
                                      assert(super.transferFrom(_from, _to, _value));
                              
                                      // transferring to the contract address destroys tokens
                                      if (_to == address(this)) {
                                          balanceOf[_to] -= _value;
                                          totalSupply -= _value;
                                          Destruction(_value);
                                      }
                              
                                      return true;
                                  }
                              }

                              File 10 of 20: BancorConverter
                              // File: contracts/token/interfaces/IERC20Token.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  ERC20 Standard Token interface
                              */
                              contract IERC20Token {
                                  // these functions aren't abstract since the compiler emits automatically generated getter functions as external
                                  function name() public view returns (string) {this;}
                                  function symbol() public view returns (string) {this;}
                                  function decimals() public view returns (uint8) {this;}
                                  function totalSupply() public view returns (uint256) {this;}
                                  function balanceOf(address _owner) public view returns (uint256) {_owner; this;}
                                  function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;}
                              
                                  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);
                              }
                              
                              // File: contracts/utility/interfaces/IWhitelist.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  Whitelist interface
                              */
                              contract IWhitelist {
                                  function isWhitelisted(address _address) public view returns (bool);
                              }
                              
                              // File: contracts/converter/interfaces/IBancorConverter.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              /*
                                  Bancor Converter interface
                              */
                              contract IBancorConverter {
                                  function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256);
                                  function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256);
                                  function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256);
                                  function conversionsEnabled() public view returns (bool) {this;}
                                  function conversionWhitelist() public view returns (IWhitelist) {this;}
                                  function conversionFee() public view returns (uint32) {this;}
                                  function reserves(address _address) public view returns (uint256, uint32, bool, bool, bool) {_address; this;}
                                  function getReserveBalance(IERC20Token _reserveToken) public view returns (uint256);
                                  function reserveTokens(uint256 _index) public view returns (IERC20Token) {_index; this;}
                                  // deprecated, backward compatibility
                                  function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
                                  function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
                                  function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
                                  function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool);
                                  function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256);
                                  function connectorTokens(uint256 _index) public view returns (IERC20Token);
                                  function connectorTokenCount() public view returns (uint16);
                              }
                              
                              // File: contracts/converter/interfaces/IBancorConverterUpgrader.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              /*
                                  Bancor Converter Upgrader interface
                              */
                              contract IBancorConverterUpgrader {
                                  function upgrade(bytes32 _version) public;
                                  function upgrade(uint16 _version) public;
                              }
                              
                              // File: contracts/converter/interfaces/IBancorFormula.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  Bancor Formula interface
                              */
                              contract IBancorFormula {
                                  function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256);
                                  function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256);
                                  function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256);
                                  function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256);
                                  function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256);
                                  // deprecated, backward compatibility
                                  function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
                              }
                              
                              // File: contracts/IBancorNetwork.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              /*
                                  Bancor Network interface
                              */
                              contract IBancorNetwork {
                                  function convert2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public payable returns (uint256);
                              
                                  function claimAndConvert2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public returns (uint256);
                              
                                  function convertFor2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public payable returns (uint256);
                              
                                  function claimAndConvertFor2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public returns (uint256);
                              
                                  function convertForPrioritized4(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256[] memory _signature,
                                      address _affiliateAccount,
                                      uint256 _affiliateFee
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convert(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function claimAndConvert(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn
                                  ) public returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convertFor(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function claimAndConvertFor(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for
                                  ) public returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convertForPrioritized3(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _customVal,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convertForPrioritized2(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  ) public payable returns (uint256);
                              
                                  // deprecated, backward compatibility
                                  function convertForPrioritized(
                                      IERC20Token[] _path,
                                      uint256 _amount,
                                      uint256 _minReturn,
                                      address _for,
                                      uint256 _block,
                                      uint256 _nonce,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  ) public payable returns (uint256);
                              }
                              
                              // File: contracts/FeatureIds.sol
                              
                              pragma solidity 0.4.26;
                              
                              /**
                                * @dev Id definitions for bancor contract features
                                * 
                                * Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract
                              */
                              contract FeatureIds {
                                  // converter features
                                  uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0;
                              }
                              
                              // File: contracts/utility/interfaces/IOwned.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  Owned contract interface
                              */
                              contract IOwned {
                                  // this function isn't abstract since the compiler emits automatically generated getter functions as external
                                  function owner() public view returns (address) {this;}
                              
                                  function transferOwnership(address _newOwner) public;
                                  function acceptOwnership() public;
                              }
                              
                              // File: contracts/utility/Owned.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              /**
                                * @dev Provides support and utilities for contract ownership
                              */
                              contract Owned is IOwned {
                                  address public owner;
                                  address public newOwner;
                              
                                  /**
                                    * @dev triggered when the owner is updated
                                    * 
                                    * @param _prevOwner previous owner
                                    * @param _newOwner  new owner
                                  */
                                  event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
                              
                                  /**
                                    * @dev initializes a new Owned instance
                                  */
                                  constructor() public {
                                      owner = msg.sender;
                                  }
                              
                                  // allows execution by the owner only
                                  modifier ownerOnly {
                                      require(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);
                                      emit OwnerUpdate(owner, newOwner);
                                      owner = newOwner;
                                      newOwner = address(0);
                                  }
                              }
                              
                              // File: contracts/utility/Managed.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              /**
                                * @dev Provides support and utilities for contract management
                                * Note that a managed contract must also have an owner
                              */
                              contract Managed is Owned {
                                  address public manager;
                                  address public newManager;
                              
                                  /**
                                    * @dev triggered when the manager is updated
                                    * 
                                    * @param _prevManager previous manager
                                    * @param _newManager  new manager
                                  */
                                  event ManagerUpdate(address indexed _prevManager, address indexed _newManager);
                              
                                  /**
                                    * @dev initializes a new Managed instance
                                  */
                                  constructor() public {
                                      manager = msg.sender;
                                  }
                              
                                  // allows execution by the manager only
                                  modifier managerOnly {
                                      assert(msg.sender == manager);
                                      _;
                                  }
                              
                                  // allows execution by either the owner or the manager only
                                  modifier ownerOrManagerOnly {
                                      require(msg.sender == owner || 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 ownerOrManagerOnly {
                                      require(_newManager != manager);
                                      newManager = _newManager;
                                  }
                              
                                  /**
                                    * @dev used by a new manager to accept a management transfer
                                  */
                                  function acceptManagement() public {
                                      require(msg.sender == newManager);
                                      emit ManagerUpdate(manager, newManager);
                                      manager = newManager;
                                      newManager = address(0);
                                  }
                              }
                              
                              // File: contracts/utility/SafeMath.sol
                              
                              pragma solidity 0.4.26;
                              
                              /**
                                * @dev Library for basic math operations with overflow/underflow protection
                              */
                              library SafeMath {
                                  /**
                                    * @dev returns the sum of _x and _y, reverts if the calculation overflows
                                    * 
                                    * @param _x   value 1
                                    * @param _y   value 2
                                    * 
                                    * @return sum
                                  */
                                  function add(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      uint256 z = _x + _y;
                                      require(z >= _x);
                                      return z;
                                  }
                              
                                  /**
                                    * @dev returns the difference of _x minus _y, reverts if the calculation underflows
                                    * 
                                    * @param _x   minuend
                                    * @param _y   subtrahend
                                    * 
                                    * @return difference
                                  */
                                  function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      require(_x >= _y);
                                      return _x - _y;
                                  }
                              
                                  /**
                                    * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows
                                    * 
                                    * @param _x   factor 1
                                    * @param _y   factor 2
                                    * 
                                    * @return product
                                  */
                                  function mul(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      // gas optimization
                                      if (_x == 0)
                                          return 0;
                              
                                      uint256 z = _x * _y;
                                      require(z / _x == _y);
                                      return z;
                                  }
                              
                                    /**
                                      * ev Integer division of two numbers truncating the quotient, reverts on division by zero.
                                      * 
                                      * aram _x   dividend
                                      * aram _y   divisor
                                      * 
                                      * eturn quotient
                                  */
                                  function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      require(_y > 0);
                                      uint256 c = _x / _y;
                              
                                      return c;
                                  }
                              }
                              
                              // File: contracts/utility/Utils.sol
                              
                              pragma solidity 0.4.26;
                              
                              /**
                                * @dev Utilities & Common Modifiers
                              */
                              contract Utils {
                                  /**
                                    * constructor
                                  */
                                  constructor() public {
                                  }
                              
                                  // 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 != address(0));
                                      _;
                                  }
                              
                                  // verifies that the address is different than this contract address
                                  modifier notThis(address _address) {
                                      require(_address != address(this));
                                      _;
                                  }
                              
                              }
                              
                              // File: contracts/utility/interfaces/IContractRegistry.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  Contract Registry interface
                              */
                              contract IContractRegistry {
                                  function addressOf(bytes32 _contractName) public view returns (address);
                              
                                  // deprecated, backward compatibility
                                  function getAddress(bytes32 _contractName) public view returns (address);
                              }
                              
                              // File: contracts/utility/ContractRegistryClient.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              
                              /**
                                * @dev Base contract for ContractRegistry clients
                              */
                              contract ContractRegistryClient is Owned, Utils {
                                  bytes32 internal constant CONTRACT_FEATURES = "ContractFeatures";
                                  bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
                                  bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
                                  bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
                                  bytes32 internal constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit";
                                  bytes32 internal constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory";
                                  bytes32 internal constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader";
                                  bytes32 internal constant BANCOR_CONVERTER_REGISTRY = "BancorConverterRegistry";
                                  bytes32 internal constant BANCOR_CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
                                  bytes32 internal constant BNT_TOKEN = "BNTToken";
                                  bytes32 internal constant BANCOR_X = "BancorX";
                                  bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
                              
                                  IContractRegistry public registry;      // address of the current contract-registry
                                  IContractRegistry public prevRegistry;  // address of the previous contract-registry
                                  bool public adminOnly;                  // only an administrator can update the contract-registry
                              
                                  /**
                                    * @dev verifies that the caller is mapped to the given contract name
                                    * 
                                    * @param _contractName    contract name
                                  */
                                  modifier only(bytes32 _contractName) {
                                      require(msg.sender == addressOf(_contractName));
                                      _;
                                  }
                              
                                  /**
                                    * @dev initializes a new ContractRegistryClient instance
                                    * 
                                    * @param  _registry   address of a contract-registry contract
                                  */
                                  constructor(IContractRegistry _registry) internal validAddress(_registry) {
                                      registry = IContractRegistry(_registry);
                                      prevRegistry = IContractRegistry(_registry);
                                  }
                              
                                  /**
                                    * @dev updates to the new contract-registry
                                   */
                                  function updateRegistry() public {
                                      // verify that this function is permitted
                                      require(!adminOnly || isAdmin());
                              
                                      // get the new contract-registry
                                      address newRegistry = addressOf(CONTRACT_REGISTRY);
                              
                                      // verify that the new contract-registry is different and not zero
                                      require(newRegistry != address(registry) && newRegistry != address(0));
                              
                                      // verify that the new contract-registry is pointing to a non-zero contract-registry
                                      require(IContractRegistry(newRegistry).addressOf(CONTRACT_REGISTRY) != address(0));
                              
                                      // save a backup of the current contract-registry before replacing it
                                      prevRegistry = registry;
                              
                                      // replace the current contract-registry with the new contract-registry
                                      registry = IContractRegistry(newRegistry);
                                  }
                              
                                  /**
                                    * @dev restores the previous contract-registry
                                  */
                                  function restoreRegistry() public {
                                      // verify that this function is permitted
                                      require(isAdmin());
                              
                                      // restore the previous contract-registry
                                      registry = prevRegistry;
                                  }
                              
                                  /**
                                    * @dev restricts the permission to update the contract-registry
                                    * 
                                    * @param _adminOnly    indicates whether or not permission is restricted to administrator only
                                  */
                                  function restrictRegistryUpdate(bool _adminOnly) public {
                                      // verify that this function is permitted
                                      require(adminOnly != _adminOnly && isAdmin());
                              
                                      // change the permission to update the contract-registry
                                      adminOnly = _adminOnly;
                                  }
                              
                                  /**
                                    * @dev returns whether or not the caller is an administrator
                                   */
                                  function isAdmin() internal view returns (bool) {
                                      return msg.sender == owner;
                                  }
                              
                                  /**
                                    * @dev returns the address associated with the given contract name
                                    * 
                                    * @param _contractName    contract name
                                    * 
                                    * @return contract address
                                  */
                                  function addressOf(bytes32 _contractName) internal view returns (address) {
                                      return registry.addressOf(_contractName);
                                  }
                              }
                              
                              // File: contracts/utility/interfaces/IContractFeatures.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  Contract Features interface
                              */
                              contract IContractFeatures {
                                  function isSupported(address _contract, uint256 _features) public view returns (bool);
                                  function enableFeatures(uint256 _features, bool _enable) public;
                              }
                              
                              // File: contracts/utility/interfaces/IAddressList.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  Address list interface
                              */
                              contract IAddressList {
                                  mapping (address => bool) public listedAddresses;
                              }
                              
                              // File: contracts/token/interfaces/ISmartToken.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              /*
                                  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;
                              }
                              
                              // File: contracts/token/interfaces/ISmartTokenController.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              /*
                                  Smart Token Controller interface
                              */
                              contract ISmartTokenController {
                                  function claimTokens(address _from, uint256 _amount) public;
                                  function token() public view returns (ISmartToken) {this;}
                              }
                              
                              // File: contracts/utility/interfaces/ITokenHolder.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              /*
                                  Token Holder interface
                              */
                              contract ITokenHolder is IOwned {
                                  function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
                              }
                              
                              // File: contracts/token/interfaces/INonStandardERC20.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve
                              */
                              contract INonStandardERC20 {
                                  // these functions aren't abstract since the compiler emits automatically generated getter functions as external
                                  function name() public view returns (string) {this;}
                                  function symbol() public view returns (string) {this;}
                                  function decimals() public view returns (uint8) {this;}
                                  function totalSupply() public view returns (uint256) {this;}
                                  function balanceOf(address _owner) public view returns (uint256) {_owner; this;}
                                  function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;}
                              
                                  function transfer(address _to, uint256 _value) public;
                                  function transferFrom(address _from, address _to, uint256 _value) public;
                                  function approve(address _spender, uint256 _value) public;
                              }
                              
                              // File: contracts/utility/TokenHolder.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              
                              
                              
                              /**
                                * @dev 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.
                                * 
                                * Note that we use the non standard ERC-20 interface which has no return value for transfer
                                * in order to support both non standard as well as standard token contracts.
                                * see https://github.com/ethereum/solidity/issues/4116
                              */
                              contract TokenHolder is ITokenHolder, Owned, Utils {
                                  /**
                                    * @dev initializes a new TokenHolder instance
                                  */
                                  constructor() public {
                                  }
                              
                                  /**
                                    * @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)
                                  {
                                      INonStandardERC20(_token).transfer(_to, _amount);
                                  }
                              }
                              
                              // File: contracts/token/SmartTokenController.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              
                              /**
                                * @dev 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 ISmartTokenController, TokenHolder {
                                  ISmartToken public token;   // Smart Token contract
                                  address public bancorX;     // BancorX contract
                              
                                  /**
                                    * @dev initializes a new SmartTokenController instance
                                    * 
                                    * @param  _token      smart token governed by the controller
                                  */
                                  constructor(ISmartToken _token)
                                      public
                                      validAddress(_token)
                                  {
                                      token = _token;
                                  }
                              
                                  // ensures that the controller is the token's owner
                                  modifier active() {
                                      require(token.owner() == address(this));
                                      _;
                                  }
                              
                                  // ensures that the controller is not the token's owner
                                  modifier inactive() {
                                      require(token.owner() != address(this));
                                      _;
                                  }
                              
                                  /**
                                    * @dev allows transferring the token ownership
                                    * the new owner needs 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 withdraws tokens held by the controller 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);
                                  }
                              
                                  /**
                                    * @dev allows the associated BancorX contract to claim tokens from any address (so that users
                                    * dont have to first give allowance when calling BancorX)
                                    * 
                                    * @param _from      address to claim the tokens from
                                    * @param _amount    the amount of tokens to claim
                                   */
                                  function claimTokens(address _from, uint256 _amount) public {
                                      // only the associated BancorX contract may call this method
                                      require(msg.sender == bancorX);
                              
                                      // destroy the tokens belonging to _from, and issue the same amount to bancorX
                                      token.destroy(_from, _amount);
                                      token.issue(msg.sender, _amount);
                                  }
                              
                                  /**
                                    * @dev allows the owner to set the associated BancorX contract
                                    * @param _bancorX    BancorX contract
                                   */
                                  function setBancorX(address _bancorX) public ownerOnly {
                                      bancorX = _bancorX;
                                  }
                              }
                              
                              // File: contracts/token/interfaces/IEtherToken.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              /*
                                  Ether Token interface
                              */
                              contract IEtherToken is ITokenHolder, IERC20Token {
                                  function deposit() public payable;
                                  function withdraw(uint256 _amount) public;
                                  function withdrawTo(address _to, uint256 _amount) public;
                              }
                              
                              // File: contracts/bancorx/interfaces/IBancorX.sol
                              
                              pragma solidity 0.4.26;
                              
                              contract IBancorX {
                                  function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) public;
                                  function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256);
                              }
                              
                              // File: contracts/converter/BancorConverter.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              
                              
                              
                              
                              
                              
                              
                              
                              
                              
                              
                              
                              
                              /**
                                * @dev Bancor Converter
                                * 
                                * The Bancor converter allows for conversions between a Smart Token and other ERC20 tokens and between different ERC20 tokens and themselves. 
                                * 
                                * The ERC20 reserve balance can be virtual, meaning that conversions between reserve tokens are based on the virtual balance instead of relying on the actual reserve balance.
                                * 
                                * This mechanism opens the possibility to create different financial tools (for example, lower slippage in conversions).
                                * 
                                * The converter is upgradable (just like any SmartTokenController) and all upgrades are opt-in. 
                                * 
                                * 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
                                *     - gas price limit check can be skipped if the transaction comes from a trusted, whitelisted signer
                                * 
                                * Other potential solutions might include a commit/reveal based schemes
                                * - Possibly add getters for the reserve fields so that the client won't need to rely on the order in the struct
                              */
                              contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractRegistryClient, FeatureIds {
                                  using SafeMath for uint256;
                              
                                  uint32 private constant RATIO_RESOLUTION = 1000000;
                                  uint64 private constant CONVERSION_FEE_RESOLUTION = 1000000;
                              
                                  struct Reserve {
                                      uint256 virtualBalance;         // reserve virtual balance
                                      uint32 ratio;                   // reserve ratio, represented in ppm, 1-1000000
                                      bool isVirtualBalanceEnabled;   // true if virtual balance is enabled, false if not
                                      bool isSaleEnabled;             // is sale of the reserve token enabled, can be set by the owner
                                      bool isSet;                     // used to tell if the mapping element is defined
                                  }
                              
                                  /**
                                    * @dev version number
                                  */
                                  uint16 public version = 23;
                                  string public converterType = 'bancor';
                              
                                  IWhitelist public conversionWhitelist;              // whitelist contract with list of addresses that are allowed to use the converter
                                  IERC20Token[] public reserveTokens;                 // ERC20 standard token addresses (prior version 17, use 'connectorTokens' instead)
                                  mapping (address => Reserve) public reserves;       // reserve token addresses -> reserve data (prior version 17, use 'connectors' instead)
                                  uint32 private totalReserveRatio = 0;               // used to efficiently prevent increasing the total reserve ratio 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
                              
                                  /**
                                    * @dev triggered when a conversion between two tokens occurs
                                    * 
                                    * @param _fromToken       ERC20 token converted from
                                    * @param _toToken         ERC20 token converted to
                                    * @param _trader          wallet that initiated the trade
                                    * @param _amount          amount converted, in fromToken
                                    * @param _return          amount returned, minus conversion fee
                                    * @param _conversionFee   conversion fee
                                  */
                                  event Conversion(
                                      address indexed _fromToken,
                                      address indexed _toToken,
                                      address indexed _trader,
                                      uint256 _amount,
                                      uint256 _return,
                                      int256 _conversionFee
                                  );
                              
                                  /**
                                    * @dev triggered after a conversion with new price data
                                    * 
                                    * @param  _connectorToken     reserve token
                                    * @param  _tokenSupply        smart token supply
                                    * @param  _connectorBalance   reserve balance
                                    * @param  _connectorWeight    reserve ratio
                                  */
                                  event PriceDataUpdate(
                                      address indexed _connectorToken,
                                      uint256 _tokenSupply,
                                      uint256 _connectorBalance,
                                      uint32 _connectorWeight
                                  );
                              
                                  /**
                                    * @dev triggered when the conversion fee is updated
                                    * 
                                    * @param  _prevFee    previous fee percentage, represented in ppm
                                    * @param  _newFee     new fee percentage, represented in ppm
                                  */
                                  event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
                              
                                  /**
                                    * @dev triggered when conversions are enabled/disabled
                                    * 
                                    * @param  _conversionsEnabled true if conversions are enabled, false if not
                                  */
                                  event ConversionsEnable(bool _conversionsEnabled);
                              
                                  /**
                                    * @dev triggered when virtual balances are enabled/disabled
                                    * 
                                    * @param  _enabled true if virtual balances are enabled, false if not
                                  */
                                  event VirtualBalancesEnable(bool _enabled);
                              
                                  /**
                                    * @dev initializes a new BancorConverter instance
                                    * 
                                    * @param  _token              smart token governed by the converter
                                    * @param  _registry           address of a contract registry contract
                                    * @param  _maxConversionFee   maximum conversion fee, represented in ppm
                                    * @param  _reserveToken       optional, initial reserve, allows defining the first reserve at deployment time
                                    * @param  _reserveRatio       optional, ratio for the initial reserve
                                  */
                                  constructor(
                                      ISmartToken _token,
                                      IContractRegistry _registry,
                                      uint32 _maxConversionFee,
                                      IERC20Token _reserveToken,
                                      uint32 _reserveRatio
                                  )   ContractRegistryClient(_registry)
                                      public
                                      SmartTokenController(_token)
                                      validConversionFee(_maxConversionFee)
                                  {
                                      IContractFeatures features = IContractFeatures(addressOf(CONTRACT_FEATURES));
                              
                                      // initialize supported features
                                      if (features != address(0))
                                          features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true);
                              
                                      maxConversionFee = _maxConversionFee;
                              
                                      if (_reserveToken != address(0))
                                          addReserve(_reserveToken, _reserveRatio);
                                  }
                              
                                  // validates a reserve token address - verifies that the address belongs to one of the reserve tokens
                                  modifier validReserve(IERC20Token _address) {
                                      require(reserves[_address].isSet);
                                      _;
                                  }
                              
                                  // validates conversion fee
                                  modifier validConversionFee(uint32 _conversionFee) {
                                      require(_conversionFee >= 0 && _conversionFee <= CONVERSION_FEE_RESOLUTION);
                                      _;
                                  }
                              
                                  // validates reserve ratio
                                  modifier validReserveRatio(uint32 _ratio) {
                                      require(_ratio > 0 && _ratio <= RATIO_RESOLUTION);
                                      _;
                                  }
                              
                                  // allows execution only when conversions aren't disabled
                                  modifier conversionsAllowed {
                                      require(conversionsEnabled);
                                      _;
                                  }
                              
                                  // allows execution only if the total-supply of the token is greater than zero
                                  modifier totalSupplyGreaterThanZeroOnly {
                                      require(token.totalSupply() > 0);
                                      _;
                                  }
                              
                                  // allows execution only on a multiple-reserve converter
                                  modifier multipleReservesOnly {
                                      require(reserveTokens.length > 1);
                                      _;
                                  }
                              
                                  /**
                                    * @dev returns the number of reserve tokens defined
                                    * note that prior to version 17, you should use 'connectorTokenCount' instead
                                    * 
                                    * @return number of reserve tokens
                                  */
                                  function reserveTokenCount() public view returns (uint16) {
                                      return uint16(reserveTokens.length);
                                  }
                              
                                  /**
                                    * @dev allows the owner to update & enable the conversion whitelist contract address
                                    * when set, only addresses that are whitelisted are actually allowed to use the converter
                                    * note that the whitelist check is actually done by the BancorNetwork contract
                                    * 
                                    * @param _whitelist    address of a whitelist contract
                                  */
                                  function setConversionWhitelist(IWhitelist _whitelist)
                                      public
                                      ownerOnly
                                      notThis(_whitelist)
                                  {
                                      conversionWhitelist = _whitelist;
                                  }
                              
                                  /**
                                    * @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 ownerOrManagerOnly {
                                      if (conversionsEnabled == _disable) {
                                          conversionsEnabled = !_disable;
                                          emit ConversionsEnable(conversionsEnabled);
                                      }
                                  }
                              
                                  /**
                                    * @dev allows transferring the token ownership
                                    * the new owner needs to accept the transfer
                                    * can only be called by the contract owner
                                    * note that token ownership can only be transferred while the owner is the converter upgrader contract
                                    * 
                                    * @param _newOwner    new token owner
                                  */
                                  function transferTokenOwnership(address _newOwner)
                                      public
                                      ownerOnly
                                      only(BANCOR_CONVERTER_UPGRADER)
                                  {
                                      super.transferTokenOwnership(_newOwner);
                                  }
                              
                                  /**
                                    * @dev used by a new owner to accept a token ownership transfer
                                    * can only be called by the contract owner
                                    * note that token ownership can only be accepted if its total-supply is greater than zero
                                  */
                                  function acceptTokenOwnership()
                                      public
                                      ownerOnly
                                      totalSupplyGreaterThanZeroOnly
                                  {
                                      super.acceptTokenOwnership();
                                  }
                              
                                  /**
                                    * @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
                                      ownerOrManagerOnly
                                  {
                                      require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
                                      emit ConversionFeeUpdate(conversionFee, _conversionFee);
                                      conversionFee = _conversionFee;
                                  }
                              
                                  /**
                                    * @dev given a return amount, returns the amount minus the conversion fee
                                    * 
                                    * @param _amount      return amount
                                    * @param _magnitude   1 for standard conversion, 2 for cross reserve conversion
                                    * 
                                    * @return return amount minus conversion fee
                                  */
                                  function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) {
                                      return _amount.mul((CONVERSION_FEE_RESOLUTION - conversionFee) ** _magnitude).div(CONVERSION_FEE_RESOLUTION ** _magnitude);
                                  }
                              
                                  /**
                                    * @dev withdraws tokens held by the converter and sends them to an account
                                    * can only be called by the owner
                                    * note that reserve tokens can only be withdrawn by the owner while the converter is inactive
                                    * unless the owner is the converter upgrader contract
                                    * 
                                    * @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 {
                                      address converterUpgrader = addressOf(BANCOR_CONVERTER_UPGRADER);
                              
                                      // if the token is not a reserve token, allow withdrawal
                                      // otherwise verify that the converter is inactive or that the owner is the upgrader contract
                                      require(!reserves[_token].isSet || token.owner() != address(this) || owner == converterUpgrader);
                                      super.withdrawTokens(_token, _to, _amount);
                                  }
                              
                                  /**
                                    * @dev upgrades the converter to the latest version
                                    * can only be called by the owner
                                    * note that the owner needs to call acceptOwnership/acceptManagement on the new converter after the upgrade
                                  */
                                  function upgrade() public ownerOnly {
                                      IBancorConverterUpgrader converterUpgrader = IBancorConverterUpgrader(addressOf(BANCOR_CONVERTER_UPGRADER));
                              
                                      transferOwnership(converterUpgrader);
                                      converterUpgrader.upgrade(version);
                                      acceptOwnership();
                                  }
                              
                                  /**
                                    * @dev defines a new reserve for the token
                                    * can only be called by the owner while the converter is inactive
                                    * note that prior to version 17, you should use 'addConnector' instead
                                    * 
                                    * @param _token                  address of the reserve token
                                    * @param _ratio                  constant reserve ratio, represented in ppm, 1-1000000
                                  */
                                  function addReserve(IERC20Token _token, uint32 _ratio)
                                      public
                                      ownerOnly
                                      inactive
                                      validAddress(_token)
                                      notThis(_token)
                                      validReserveRatio(_ratio)
                                  {
                                      require(_token != token && !reserves[_token].isSet && totalReserveRatio + _ratio <= RATIO_RESOLUTION); // validate input
                              
                                      reserves[_token].ratio = _ratio;
                                      reserves[_token].isVirtualBalanceEnabled = false;
                                      reserves[_token].virtualBalance = 0;
                                      reserves[_token].isSaleEnabled = true;
                                      reserves[_token].isSet = true;
                                      reserveTokens.push(_token);
                                      totalReserveRatio += _ratio;
                                  }
                              
                                  /**
                                    * @dev updates a reserve's virtual balance
                                    * only used during an upgrade process
                                    * can only be called by the contract owner while the owner is the converter upgrader contract
                                    * note that prior to version 17, you should use 'updateConnector' instead
                                    * 
                                    * @param _reserveToken    address of the reserve token
                                    * @param _virtualBalance  new reserve virtual balance, or 0 to disable virtual balance
                                  */
                                  function updateReserveVirtualBalance(IERC20Token _reserveToken, uint256 _virtualBalance)
                                      public
                                      ownerOnly
                                      only(BANCOR_CONVERTER_UPGRADER)
                                      validReserve(_reserveToken)
                                  {
                                      Reserve storage reserve = reserves[_reserveToken];
                                      reserve.isVirtualBalanceEnabled = _virtualBalance != 0;
                                      reserve.virtualBalance = _virtualBalance;
                                  }
                              
                                  /**
                                    * @dev enables virtual balance for the reserves
                                    * virtual balance only affects conversions between reserve tokens
                                    * virtual balance of all reserves can only scale by the same factor, to keep the ratio between them the same
                                    * note that the balance is determined during the execution of this function and set statically -
                                    * meaning that it's not calculated dynamically based on the factor after each conversion
                                    * can only be called by the contract owner while the converter is active
                                    * 
                                    * @param _scaleFactor  percentage, 100-1000 (100 = no virtual balance, 1000 = virtual balance = actual balance * 10)
                                  */
                                  function enableVirtualBalances(uint16 _scaleFactor)
                                      public
                                      ownerOnly
                                      active
                                  {
                                      // validate input
                                      require(_scaleFactor >= 100 && _scaleFactor <= 1000);
                                      bool enable = _scaleFactor != 100;
                              
                                      // iterate through the reserves and scale their balance by the ratio provided,
                                      // or disable virtual balance altogether if a factor of 100% is passed in
                                      IERC20Token reserveToken;
                                      for (uint16 i = 0; i < reserveTokens.length; i++) {
                                          reserveToken = reserveTokens[i];
                                          Reserve storage reserve = reserves[reserveToken];
                                          reserve.isVirtualBalanceEnabled = enable;
                                          reserve.virtualBalance = enable ? reserveToken.balanceOf(this).mul(_scaleFactor).div(100) : 0;
                                      }
                              
                                      emit VirtualBalancesEnable(enable);
                                  }
                              
                                  /**
                                    * @dev disables converting from the given reserve token in case the reserve token got compromised
                                    * can only be called by the owner
                                    * note that converting to the token is still enabled regardless of this flag and it cannot be disabled by the owner
                                    * note that prior to version 17, you should use 'disableConnectorSale' instead
                                    * 
                                    * @param _reserveToken    reserve token contract address
                                    * @param _disable         true to disable the token, false to re-enable it
                                  */
                                  function disableReserveSale(IERC20Token _reserveToken, bool _disable)
                                      public
                                      ownerOnly
                                      validReserve(_reserveToken)
                                  {
                                      reserves[_reserveToken].isSaleEnabled = !_disable;
                                  }
                              
                                  /**
                                    * @dev returns the reserve's ratio
                                    * added in version 22
                                    * 
                                    * @param _reserveToken    reserve token contract address
                                    * 
                                    * @return reserve ratio
                                  */
                                  function getReserveRatio(IERC20Token _reserveToken)
                                      public
                                      view
                                      validReserve(_reserveToken)
                                      returns (uint256)
                                  {
                                      return reserves[_reserveToken].ratio;
                                  }
                              
                                  /**
                                    * @dev returns the reserve's virtual balance if one is defined, otherwise returns the actual balance
                                    * note that prior to version 17, you should use 'getConnectorBalance' instead
                                    * 
                                    * @param _reserveToken    reserve token contract address
                                    * 
                                    * @return reserve balance
                                  */
                                  function getReserveBalance(IERC20Token _reserveToken)
                                      public
                                      view
                                      validReserve(_reserveToken)
                                      returns (uint256)
                                  {
                                      Reserve storage reserve = reserves[_reserveToken];
                                      return reserve.isVirtualBalanceEnabled ? reserve.virtualBalance : _reserveToken.balanceOf(this);
                                  }
                              
                                  /**
                                    * @dev calculates the expected return of converting a given amount of tokens
                                    * 
                                    * @param _fromToken  contract address of the token to convert from
                                    * @param _toToken    contract address of the token to convert to
                                    * @param _amount     amount of tokens received from the user
                                    * 
                                    * @return amount of tokens that the user will receive
                                    * @return amount of tokens that the user will pay as fee
                                  */
                                  function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256) {
                                      require(_fromToken != _toToken); // validate input
                              
                                      // conversion between the token and one of its reserves
                                      if (_toToken == token)
                                          return getPurchaseReturn(_fromToken, _amount);
                                      else if (_fromToken == token)
                                          return getSaleReturn(_toToken, _amount);
                              
                                      // conversion between 2 reserves
                                      return getCrossReserveReturn(_fromToken, _toToken, _amount);
                                  }
                              
                                  /**
                                    * @dev calculates the expected return of buying with a given amount of tokens
                                    * 
                                    * @param _reserveToken    contract address of the reserve token
                                    * @param _depositAmount   amount of reserve-tokens received from the user
                                    * 
                                    * @return amount of supply-tokens that the user will receive
                                    * @return amount of supply-tokens that the user will pay as fee
                                  */
                                  function getPurchaseReturn(IERC20Token _reserveToken, uint256 _depositAmount)
                                      public
                                      view
                                      active
                                      validReserve(_reserveToken)
                                      returns (uint256, uint256)
                                  {
                                      Reserve storage reserve = reserves[_reserveToken];
                                      require(reserve.isSaleEnabled); // validate input
                              
                                      uint256 tokenSupply = token.totalSupply();
                                      uint256 reserveBalance = _reserveToken.balanceOf(this);
                                      IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
                                      uint256 amount = formula.calculatePurchaseReturn(tokenSupply, reserveBalance, reserve.ratio, _depositAmount);
                                      uint256 finalAmount = getFinalAmount(amount, 1);
                              
                                      // return the amount minus the conversion fee and the conversion fee
                                      return (finalAmount, amount - finalAmount);
                                  }
                              
                                  /**
                                    * @dev calculates the expected return of selling a given amount of tokens
                                    * 
                                    * @param _reserveToken    contract address of the reserve token
                                    * @param _sellAmount      amount of supply-tokens received from the user
                                    * 
                                    * @return amount of reserve-tokens that the user will receive
                                    * @return amount of reserve-tokens that the user will pay as fee
                                  */
                                  function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount)
                                      public
                                      view
                                      active
                                      validReserve(_reserveToken)
                                      returns (uint256, uint256)
                                  {
                                      Reserve storage reserve = reserves[_reserveToken];
                                      uint256 tokenSupply = token.totalSupply();
                                      uint256 reserveBalance = _reserveToken.balanceOf(this);
                                      IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
                                      uint256 amount = formula.calculateSaleReturn(tokenSupply, reserveBalance, reserve.ratio, _sellAmount);
                                      uint256 finalAmount = getFinalAmount(amount, 1);
                              
                                      // return the amount minus the conversion fee and the conversion fee
                                      return (finalAmount, amount - finalAmount);
                                  }
                              
                                  /**
                                    * @dev calculates the expected return of converting a given amount from one reserve to another
                                    * note that prior to version 17, you should use 'getCrossConnectorReturn' instead
                                    * 
                                    * @param _fromReserveToken    contract address of the reserve token to convert from
                                    * @param _toReserveToken      contract address of the reserve token to convert to
                                    * @param _amount              amount of tokens received from the user
                                    * 
                                    * @return amount of tokens that the user will receive
                                    * @return amount of tokens that the user will pay as fee
                                  */
                                  function getCrossReserveReturn(IERC20Token _fromReserveToken, IERC20Token _toReserveToken, uint256 _amount)
                                      public
                                      view
                                      active
                                      validReserve(_fromReserveToken)
                                      validReserve(_toReserveToken)
                                      returns (uint256, uint256)
                                  {
                                      Reserve storage fromReserve = reserves[_fromReserveToken];
                                      Reserve storage toReserve = reserves[_toReserveToken];
                                      require(fromReserve.isSaleEnabled); // validate input
                              
                                      IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
                                      uint256 amount = formula.calculateCrossReserveReturn(
                                          getReserveBalance(_fromReserveToken), 
                                          fromReserve.ratio, 
                                          getReserveBalance(_toReserveToken), 
                                          toReserve.ratio, 
                                          _amount);
                                      uint256 finalAmount = getFinalAmount(amount, 2);
                              
                                      // return the amount minus the conversion fee and the conversion fee
                                      // the fee is higher (magnitude = 2) since cross reserve conversion equals 2 conversions (from / to the smart token)
                                      return (finalAmount, amount - finalAmount);
                                  }
                              
                                  /**
                                    * @dev converts a specific amount of _fromToken to _toToken
                                    * can only be called by the bancor network contract
                                    * 
                                    * @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 convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn)
                                      public
                                      only(BANCOR_NETWORK)
                                      conversionsAllowed
                                      greaterThanZero(_minReturn)
                                      returns (uint256)
                                  {
                                      require(_fromToken != _toToken); // validate input
                              
                                      // conversion between the token and one of its reserves
                                      if (_toToken == token)
                                          return buy(_fromToken, _amount, _minReturn);
                                      else if (_fromToken == token)
                                          return sell(_toToken, _amount, _minReturn);
                              
                                      uint256 amount;
                                      uint256 feeAmount;
                              
                                      // conversion between 2 reserves
                                      (amount, feeAmount) = getCrossReserveReturn(_fromToken, _toToken, _amount);
                                      // ensure the trade gives something in return and meets the minimum requested amount
                                      require(amount != 0 && amount >= _minReturn);
                              
                                      // update the source token virtual balance if relevant
                                      Reserve storage fromReserve = reserves[_fromToken];
                                      if (fromReserve.isVirtualBalanceEnabled)
                                          fromReserve.virtualBalance = fromReserve.virtualBalance.add(_amount);
                              
                                      // update the target token virtual balance if relevant
                                      Reserve storage toReserve = reserves[_toToken];
                                      if (toReserve.isVirtualBalanceEnabled)
                                          toReserve.virtualBalance = toReserve.virtualBalance.sub(amount);
                              
                                      // ensure that the trade won't deplete the reserve balance
                                      uint256 toReserveBalance = getReserveBalance(_toToken);
                                      assert(amount < toReserveBalance);
                              
                                      // transfer funds from the caller in the from reserve token
                                      ensureTransferFrom(_fromToken, msg.sender, this, _amount);
                                      // transfer funds to the caller in the to reserve token
                                      // the transfer might fail if virtual balance is enabled
                                      ensureTransferFrom(_toToken, this, msg.sender, amount);
                              
                                      // dispatch the conversion event
                                      // the fee is higher (magnitude = 2) since cross reserve conversion equals 2 conversions (from / to the smart token)
                                      dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount);
                              
                                      // dispatch price data updates for the smart token / both reserves
                                      emit PriceDataUpdate(_fromToken, token.totalSupply(), _fromToken.balanceOf(this), fromReserve.ratio);
                                      emit PriceDataUpdate(_toToken, token.totalSupply(), _toToken.balanceOf(this), toReserve.ratio);
                                      return amount;
                                  }
                              
                                  /**
                                    * @dev buys the token by depositing one of its reserve tokens
                                    * 
                                    * @param _reserveToken    reserve token contract address
                                    * @param _depositAmount   amount to deposit (in the reserve 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 _reserveToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) {
                                      uint256 amount;
                                      uint256 feeAmount;
                                      (amount, feeAmount) = getPurchaseReturn(_reserveToken, _depositAmount);
                                      // ensure the trade gives something in return and meets the minimum requested amount
                                      require(amount != 0 && amount >= _minReturn);
                              
                                      // update virtual balance if relevant
                                      Reserve storage reserve = reserves[_reserveToken];
                                      if (reserve.isVirtualBalanceEnabled)
                                          reserve.virtualBalance = reserve.virtualBalance.add(_depositAmount);
                              
                                      // transfer funds from the caller in the reserve token
                                      ensureTransferFrom(_reserveToken, msg.sender, this, _depositAmount);
                                      // issue new funds to the caller in the smart token
                                      token.issue(msg.sender, amount);
                              
                                      // dispatch the conversion event
                                      dispatchConversionEvent(_reserveToken, token, _depositAmount, amount, feeAmount);
                              
                                      // dispatch price data update for the smart token/reserve
                                      emit PriceDataUpdate(_reserveToken, token.totalSupply(), _reserveToken.balanceOf(this), reserve.ratio);
                                      return amount;
                                  }
                              
                                  /**
                                    * @dev sells the token by withdrawing from one of its reserve tokens
                                    * 
                                    * @param _reserveToken    reserve 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 _reserveToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) {
                                      require(_sellAmount <= token.balanceOf(msg.sender)); // validate input
                                      uint256 amount;
                                      uint256 feeAmount;
                                      (amount, feeAmount) = getSaleReturn(_reserveToken, _sellAmount);
                                      // ensure the trade gives something in return and meets the minimum requested amount
                                      require(amount != 0 && amount >= _minReturn);
                              
                                      // ensure that the trade will only deplete the reserve balance if the total supply is depleted as well
                                      uint256 tokenSupply = token.totalSupply();
                                      uint256 reserveBalance = _reserveToken.balanceOf(this);
                                      assert(amount < reserveBalance || (amount == reserveBalance && _sellAmount == tokenSupply));
                              
                                      // update virtual balance if relevant
                                      Reserve storage reserve = reserves[_reserveToken];
                                      if (reserve.isVirtualBalanceEnabled)
                                          reserve.virtualBalance = reserve.virtualBalance.sub(amount);
                              
                                      // destroy _sellAmount from the caller's balance in the smart token
                                      token.destroy(msg.sender, _sellAmount);
                                      // transfer funds to the caller in the reserve token
                                      ensureTransferFrom(_reserveToken, this, msg.sender, amount);
                              
                                      // dispatch the conversion event
                                      dispatchConversionEvent(token, _reserveToken, _sellAmount, amount, feeAmount);
                              
                                      // dispatch price data update for the smart token/reserve
                                      emit PriceDataUpdate(_reserveToken, token.totalSupply(), _reserveToken.balanceOf(this), reserve.ratio);
                                      return amount;
                                  }
                              
                                  /**
                                    * @dev converts a specific amount of _fromToken to _toToken
                                    * note that prior to version 16, you should use 'convert' instead
                                    * 
                                    * @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
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return conversion return amount
                                  */
                                  function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) {
                                      IERC20Token[] memory path = new IERC20Token[](3);
                                      (path[0], path[1], path[2]) = (_fromToken, token, _toToken);
                                      return quickConvert2(path, _amount, _minReturn, _affiliateAccount, _affiliateFee);
                                  }
                              
                                  /**
                                    * @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
                                    * note that prior to version 16, you should use 'quickConvert' instead
                                    * 
                                    * @param _path                conversion path, see conversion path format in the BancorNetwork 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
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return tokens issued in return
                                  */
                                  function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee)
                                      public
                                      payable
                                      returns (uint256)
                                  {
                                      return quickConvertPrioritized2(_path, _amount, _minReturn, getSignature(0x0, 0x0, 0x0, 0x0, 0x0), _affiliateAccount, _affiliateFee);
                                  }
                              
                                  /**
                                    * @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
                                    * note that prior to version 16, you should use 'quickConvertPrioritized' instead
                                    * 
                                    * @param _path                conversion path, see conversion path format in the BancorNetwork 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
                                    * @param _signature           an array of the following elements:
                                    *     [0] uint256             custom value that was signed for prioritized conversion; must be equal to _amount
                                    *     [1] uint256             if the current block exceeded the given parameter - it is cancelled
                                    *     [2] uint8               (signature[128:130]) associated with the signer address and helps to validate if the signature is legit
                                    *     [3] bytes32             (signature[0:64]) associated with the signer address and helps to validate if the signature is legit
                                    *     [4] bytes32             (signature[64:128]) associated with the signer address and helps to validate if the signature is legit
                                    * if the array is empty (length == 0), then the gas-price limit is verified instead of the signature
                                    * @param _affiliateAccount    affiliate account
                                    * @param _affiliateFee        affiliate fee in PPM
                                    * 
                                    * @return tokens issued in return
                                  */
                                  function quickConvertPrioritized2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256[] memory _signature, address _affiliateAccount, uint256 _affiliateFee)
                                      public
                                      payable
                                      returns (uint256)
                                  {
                                      require(_signature.length == 0 || _signature[0] == _amount);
                              
                                      IBancorNetwork bancorNetwork = IBancorNetwork(addressOf(BANCOR_NETWORK));
                              
                                      // we need to transfer the source tokens from the caller to the BancorNetwork contract,
                                      // so it can execute the conversion on behalf of the caller
                                      if (msg.value == 0) {
                                          // not ETH, send the source tokens to the BancorNetwork contract
                                          // if the token is the smart token, no allowance is required - destroy the tokens
                                          // from the caller and issue them to the BancorNetwork contract
                                          if (_path[0] == token) {
                                              token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token
                                              token.issue(bancorNetwork, _amount); // issue _amount new tokens to the BancorNetwork contract
                                          } else {
                                              // otherwise, we assume we already have allowance, transfer the tokens directly to the BancorNetwork contract
                                              ensureTransferFrom(_path[0], msg.sender, bancorNetwork, _amount);
                                          }
                                      }
                              
                                      // execute the conversion and pass on the ETH with the call
                                      return bancorNetwork.convertForPrioritized4.value(msg.value)(_path, _amount, _minReturn, msg.sender, _signature, _affiliateAccount, _affiliateFee);
                                  }
                              
                                  /**
                                    * @dev allows a user to convert BNT that was sent from another blockchain into any other
                                    * token on the BancorNetwork without specifying the amount of BNT to be converted, but
                                    * rather by providing the xTransferId which allows us to get the amount from BancorX.
                                    * note that prior to version 16, you should use 'completeXConversion' instead
                                    * 
                                    * @param _path            conversion path, see conversion path format in the BancorNetwork contract
                                    * @param _minReturn       if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
                                    * @param _conversionId    pre-determined unique (if non zero) id which refers to this transaction 
                                    * @param _signature       an array of the following elements:
                                    *     [0] uint256         custom value that was signed for prioritized conversion; must be equal to _conversionId
                                    *     [1] uint256         if the current block exceeded the given parameter - it is cancelled
                                    *     [2] uint8           (signature[128:130]) associated with the signer address and helps to validate if the signature is legit
                                    *     [3] bytes32         (signature[0:64]) associated with the signer address and helps to validate if the signature is legit
                                    *     [4] bytes32         (signature[64:128]) associated with the signer address and helps to validate if the signature is legit
                                    * if the array is empty (length == 0), then the gas-price limit is verified instead of the signature
                                    * 
                                    * @return tokens issued in return
                                  */
                                  function completeXConversion2(
                                      IERC20Token[] _path,
                                      uint256 _minReturn,
                                      uint256 _conversionId,
                                      uint256[] memory _signature
                                  )
                                      public
                                      returns (uint256)
                                  {
                                      // verify that the custom value (if valid) is equal to _conversionId
                                      require(_signature.length == 0 || _signature[0] == _conversionId);
                              
                                      IBancorX bancorX = IBancorX(addressOf(BANCOR_X));
                                      IBancorNetwork bancorNetwork = IBancorNetwork(addressOf(BANCOR_NETWORK));
                              
                                      // verify that the first token in the path is BNT
                                      require(_path[0] == addressOf(BNT_TOKEN));
                              
                                      // get conversion amount from BancorX contract
                                      uint256 amount = bancorX.getXTransferAmount(_conversionId, msg.sender);
                              
                                      // send BNT from msg.sender to the BancorNetwork contract
                                      token.destroy(msg.sender, amount);
                                      token.issue(bancorNetwork, amount);
                              
                                      return bancorNetwork.convertForPrioritized4(_path, amount, _minReturn, msg.sender, _signature, address(0), 0);
                                  }
                              
                                  /**
                                    * @dev returns whether or not the caller is an administrator
                                   */
                                  function isAdmin() internal view returns (bool) {
                                      return msg.sender == owner || msg.sender == manager;
                                  }
                              
                                  /**
                                    * @dev ensures transfer of tokens, taking into account that some ERC-20 implementations don't return
                                    * true on success but revert on failure instead
                                    * 
                                    * @param _token     the token to transfer
                                    * @param _from      the address to transfer the tokens from
                                    * @param _to        the address to transfer the tokens to
                                    * @param _amount    the amount to transfer
                                  */
                                  function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private {
                                      // We must assume that functions `transfer` and `transferFrom` do not return anything,
                                      // because not all tokens abide the requirement of the ERC20 standard to return success or failure.
                                      // This is because in the current compiler version, the calling contract can handle more returned data than expected but not less.
                                      // This may change in the future, so that the calling contract will revert if the size of the data is not exactly what it expects.
                                      uint256 prevBalance = _token.balanceOf(_to);
                                      if (_from == address(this))
                                          INonStandardERC20(_token).transfer(_to, _amount);
                                      else
                                          INonStandardERC20(_token).transferFrom(_from, _to, _amount);
                                      uint256 postBalance = _token.balanceOf(_to);
                                      require(postBalance > prevBalance);
                                  }
                              
                                  /**
                                    * @dev buys the token with all reserve tokens using the same percentage
                                    * for example, if the caller increases the supply by 10%,
                                    * then it will cost an amount equal to 10% of each reserve token balance
                                    * note that the function can be called only when conversions are enabled
                                    * 
                                    * @param _amount  amount to increase the supply by (in the smart token)
                                  */
                                  function fund(uint256 _amount)
                                      public
                                      conversionsAllowed
                                      multipleReservesOnly
                                  {
                                      uint256 supply = token.totalSupply();
                                      IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
                              
                                      // iterate through the reserve tokens and transfer a percentage equal to the ratio between _amount
                                      // and the total supply in each reserve from the caller to the converter
                                      IERC20Token reserveToken;
                                      uint256 reserveBalance;
                                      uint256 reserveAmount;
                                      for (uint16 i = 0; i < reserveTokens.length; i++) {
                                          reserveToken = reserveTokens[i];
                                          reserveBalance = reserveToken.balanceOf(this);
                                          reserveAmount = formula.calculateFundCost(supply, reserveBalance, totalReserveRatio, _amount);
                              
                                          // update virtual balance if relevant
                                          Reserve storage reserve = reserves[reserveToken];
                                          if (reserve.isVirtualBalanceEnabled)
                                              reserve.virtualBalance = reserve.virtualBalance.add(reserveAmount);
                              
                                          // transfer funds from the caller in the reserve token
                                          ensureTransferFrom(reserveToken, msg.sender, this, reserveAmount);
                              
                                          // dispatch price data update for the smart token/reserve
                                          emit PriceDataUpdate(reserveToken, supply + _amount, reserveBalance + reserveAmount, reserve.ratio);
                                      }
                              
                                      // issue new funds to the caller in the smart token
                                      token.issue(msg.sender, _amount);
                                  }
                              
                                  /**
                                    * @dev sells the token for all reserve tokens using the same percentage
                                    * for example, if the holder sells 10% of the supply,
                                    * then they will receive 10% of each reserve token balance in return
                                    * note that the function can be called also when conversions are disabled
                                    * 
                                    * @param _amount  amount to liquidate (in the smart token)
                                  */
                                  function liquidate(uint256 _amount)
                                      public
                                      multipleReservesOnly
                                  {
                                      uint256 supply = token.totalSupply();
                                      IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
                              
                                      // destroy _amount from the caller's balance in the smart token
                                      token.destroy(msg.sender, _amount);
                              
                                      // iterate through the reserve tokens and send a percentage equal to the ratio between _amount
                                      // and the total supply from each reserve balance to the caller
                                      IERC20Token reserveToken;
                                      uint256 reserveBalance;
                                      uint256 reserveAmount;
                                      for (uint16 i = 0; i < reserveTokens.length; i++) {
                                          reserveToken = reserveTokens[i];
                                          reserveBalance = reserveToken.balanceOf(this);
                                          reserveAmount = formula.calculateLiquidateReturn(supply, reserveBalance, totalReserveRatio, _amount);
                              
                                          // update virtual balance if relevant
                                          Reserve storage reserve = reserves[reserveToken];
                                          if (reserve.isVirtualBalanceEnabled)
                                              reserve.virtualBalance = reserve.virtualBalance.sub(reserveAmount);
                              
                                          // transfer funds to the caller in the reserve token
                                          ensureTransferFrom(reserveToken, this, msg.sender, reserveAmount);
                              
                                          // dispatch price data update for the smart token/reserve
                                          emit PriceDataUpdate(reserveToken, supply - _amount, reserveBalance - reserveAmount, reserve.ratio);
                                      }
                                  }
                              
                                  /**
                                    * @dev helper, dispatches the Conversion event
                                    * 
                                    * @param _fromToken       ERC20 token to convert from
                                    * @param _toToken         ERC20 token to convert to
                                    * @param _amount          amount purchased/sold (in the source token)
                                    * @param _returnAmount    amount returned (in the target token)
                                  */
                                  function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private {
                                      // fee amount is converted to 255 bits -
                                      // negative amount means the fee is taken from the source token, positive amount means its taken from the target token
                                      // currently the fee is always taken from the target token
                                      // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow
                                      assert(_feeAmount < 2 ** 255);
                                      emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount));
                                  }
                              
                                  function getSignature(
                                      uint256 _customVal,
                                      uint256 _block,
                                      uint8 _v,
                                      bytes32 _r,
                                      bytes32 _s
                                  ) private pure returns (uint256[] memory) {
                                      if (_v == 0x0 && _r == 0x0 && _s == 0x0)
                                          return new uint256[](0);
                                      uint256[] memory signature = new uint256[](5);
                                      signature[0] = _customVal;
                                      signature[1] = _block;
                                      signature[2] = uint256(_v);
                                      signature[3] = uint256(_r);
                                      signature[4] = uint256(_s);
                                      return signature;
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
                                      return convertInternal(_fromToken, _toToken, _amount, _minReturn);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
                                      return convert2(_fromToken, _toToken, _amount, _minReturn, address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) {
                                      return quickConvert2(_path, _amount, _minReturn, address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) {
                                      return quickConvertPrioritized2(_path, _amount, _minReturn, getSignature(_amount, _block, _v, _r, _s), address(0), 0);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function completeXConversion(IERC20Token[] _path, uint256 _minReturn, uint256 _conversionId, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public returns (uint256) {
                                      return completeXConversion2(_path, _minReturn, _conversionId, getSignature(_conversionId, _block, _v, _r, _s));
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool) {
                                      Reserve storage reserve = reserves[_address];
                                      return(reserve.virtualBalance, reserve.ratio, reserve.isVirtualBalanceEnabled, reserve.isSaleEnabled, reserve.isSet);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function connectorTokens(uint256 _index) public view returns (IERC20Token) {
                                      return BancorConverter.reserveTokens[_index];
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function connectorTokenCount() public view returns (uint16) {
                                      return reserveTokenCount();
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function addConnector(IERC20Token _token, uint32 _weight, bool /*_enableVirtualBalance*/) public {
                                      addReserve(_token, _weight);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function updateConnector(IERC20Token _connectorToken, uint32 /*_weight*/, bool /*_enableVirtualBalance*/, uint256 _virtualBalance) public {
                                      updateReserveVirtualBalance(_connectorToken, _virtualBalance);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function disableConnectorSale(IERC20Token _connectorToken, bool _disable) public {
                                      disableReserveSale(_connectorToken, _disable);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256) {
                                      return getReserveBalance(_connectorToken);
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _amount) public view returns (uint256, uint256) {
                                      return getCrossReserveReturn(_fromConnectorToken, _toConnectorToken, _amount);
                                  }
                              }

                              File 11 of 20: EtherToken
                              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 owner) { owner; }
                              
                                  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;
                                  }
                              }
                              
                              /*
                                  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));
                                  }
                              }
                              
                              /*
                                  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 name) { name; }
                                  function symbol() public constant returns (string symbol) { symbol; }
                                  function decimals() public constant returns (uint8 decimals) { decimals; }
                                  function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; }
                                  function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
                                  function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; }
                              
                                  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);
                              }
                              
                              /**
                                  ERC20 Standard Token implementation
                              */
                              contract ERC20Token is IERC20Token, Utils {
                                  string public standard = 'Token 0.1';
                                  string public name = '';
                                  string public symbol = '';
                                  uint8 public decimals = 0;
                                  uint256 public totalSupply = 0;
                                  mapping (address => uint256) public balanceOf;
                                  mapping (address => mapping (address => uint256)) public allowance;
                              
                                  event Transfer(address indexed _from, address indexed _to, uint256 _value);
                                  event Approval(address indexed _owner, address indexed _spender, uint256 _value);
                              
                                  /**
                                      @dev constructor
                              
                                      @param _name        token name
                                      @param _symbol      token symbol
                                      @param _decimals    decimal points, for display purposes
                                  */
                                  function ERC20Token(string _name, string _symbol, uint8 _decimals) {
                                      require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
                              
                                      name = _name;
                                      symbol = _symbol;
                                      decimals = _decimals;
                                  }
                              
                                  /**
                                      @dev send coins
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transfer(address _to, uint256 _value)
                                      public
                                      validAddress(_to)
                                      returns (bool success)
                                  {
                                      balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
                                      balanceOf[_to] = safeAdd(balanceOf[_to], _value);
                                      Transfer(msg.sender, _to, _value);
                                      return true;
                                  }
                              
                                  /**
                                      @dev an account/contract attempts to get the coins
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      @param _from    source address
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transferFrom(address _from, address _to, uint256 _value)
                                      public
                                      validAddress(_from)
                                      validAddress(_to)
                                      returns (bool success)
                                  {
                                      allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
                                      balanceOf[_from] = safeSub(balanceOf[_from], _value);
                                      balanceOf[_to] = safeAdd(balanceOf[_to], _value);
                                      Transfer(_from, _to, _value);
                                      return true;
                                  }
                              
                                  /**
                                      @dev allow another account/contract to spend some tokens on your behalf
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      also, to minimize the risk of the approve/transferFrom attack vector
                                      (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
                                      in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
                              
                                      @param _spender approved address
                                      @param _value   allowance amount
                              
                                      @return true if the approval was successful, false if it wasn't
                                  */
                                  function approve(address _spender, uint256 _value)
                                      public
                                      validAddress(_spender)
                                      returns (bool success)
                                  {
                                      // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
                                      require(_value == 0 || allowance[msg.sender][_spender] == 0);
                              
                                      allowance[msg.sender][_spender] = _value;
                                      Approval(msg.sender, _spender, _value);
                                      return true;
                                  }
                              }
                              
                              /*
                                  Ether Token interface
                              */
                              contract IEtherToken is ITokenHolder, IERC20Token {
                                  function deposit() public payable;
                                  function withdraw(uint256 _amount) public;
                                  function withdrawTo(address _to, uint256 _amount);
                              }
                              
                              /**
                                  Ether tokenization contract
                              
                                  'Owned' is specified here for readability reasons
                              */
                              contract EtherToken is IEtherToken, Owned, ERC20Token, TokenHolder {
                                  // triggered when the total supply is increased
                                  event Issuance(uint256 _amount);
                                  // triggered when the total supply is decreased
                                  event Destruction(uint256 _amount);
                              
                                  /**
                                      @dev constructor
                                  */
                                  function EtherToken()
                                      ERC20Token('Ether Token', 'ETH', 18) {
                                  }
                              
                                  /**
                                      @dev deposit ether in the account
                                  */
                                  function deposit() public payable {
                                      balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], msg.value); // add the value to the account balance
                                      totalSupply = safeAdd(totalSupply, msg.value); // increase the total supply
                              
                                      Issuance(msg.value);
                                      Transfer(this, msg.sender, msg.value);
                                  }
                              
                                  /**
                                      @dev withdraw ether from the account
                              
                                      @param _amount  amount of ether to withdraw
                                  */
                                  function withdraw(uint256 _amount) public {
                                      withdrawTo(msg.sender, _amount);
                                  }
                              
                                  /**
                                      @dev withdraw ether from the account to a target account
                              
                                      @param _to      account to receive the ether
                                      @param _amount  amount of ether to withdraw
                                  */
                                  function withdrawTo(address _to, uint256 _amount)
                                      public
                                      notThis(_to)
                                  {
                                      balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _amount); // deduct the amount from the account balance
                                      totalSupply = safeSub(totalSupply, _amount); // decrease the total supply
                                      _to.transfer(_amount); // send the amount to the target account
                              
                                      Transfer(msg.sender, this, _amount);
                                      Destruction(_amount);
                                  }
                              
                                  // ERC20 standard method overrides with some extra protection
                              
                                  /**
                                      @dev send coins
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transfer(address _to, uint256 _value)
                                      public
                                      notThis(_to)
                                      returns (bool success)
                                  {
                                      assert(super.transfer(_to, _value));
                                      return true;
                                  }
                              
                                  /**
                                      @dev an account/contract attempts to get the coins
                                      throws on any error rather then return a false flag to minimize user errors
                              
                                      @param _from    source address
                                      @param _to      target address
                                      @param _value   transfer amount
                              
                                      @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transferFrom(address _from, address _to, uint256 _value)
                                      public
                                      notThis(_to)
                                      returns (bool success)
                                  {
                                      assert(super.transferFrom(_from, _to, _value));
                                      return true;
                                  }
                              
                                  /**
                                      @dev deposit ether in the account
                                  */
                                  function() public payable {
                                      deposit();
                                  }
                              }

                              File 12 of 20: 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 13 of 20: BancorFormula
                              pragma solidity ^0.4.21;
                              
                              /*
                                  Utilities & Common Modifiers
                              */
                              contract Utils {
                                  /**
                                      constructor
                                  */
                                  function Utils() public {
                                  }
                              
                                  // 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 != address(0));
                                      _;
                                  }
                              
                                  // 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 pure 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 pure 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 pure returns (uint256) {
                                      uint256 z = _x * _y;
                                      assert(_x == 0 || z / _x == _y);
                                      return z;
                                  }
                              }
                              
                              /*
                                  Bancor Formula interface
                              */
                              contract IBancorFormula {
                                  function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
                                  function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
                                  function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
                              }
                              
                              contract BancorFormula is IBancorFormula, Utils {
                                  string public version = '0.3';
                              
                                  uint256 private constant ONE = 1;
                                  uint32 private constant MAX_WEIGHT = 1000000;
                                  uint8 private constant MIN_PRECISION = 32;
                                  uint8 private constant MAX_PRECISION = 127;
                              
                                  /**
                                      Auto-generated via 'PrintIntScalingFactors.py'
                                  */
                                  uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
                                  uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
                                  uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
                              
                                  /**
                                      Auto-generated via 'PrintLn2ScalingFactors.py'
                                  */
                                  uint256 private constant LN2_NUMERATOR   = 0x3f80fe03f80fe03f80fe03f80fe03f8;
                                  uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
                              
                                  /**
                                      Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
                                  */
                                  uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
                                  uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
                              
                                  /**
                                      Auto-generated via 'PrintFunctionBancorFormula.py'
                                  */
                                  uint256[128] private maxExpArray;
                                  function BancorFormula() public {
                                  //  maxExpArray[  0] = 0x6bffffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  1] = 0x67ffffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  2] = 0x637fffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  3] = 0x5f6fffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  4] = 0x5b77ffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  5] = 0x57b3ffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  6] = 0x5419ffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  7] = 0x50a2ffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  8] = 0x4d517fffffffffffffffffffffffffffff;
                                  //  maxExpArray[  9] = 0x4a233fffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
                                  //  maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
                                  //  maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
                                  //  maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
                                  //  maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
                                  //  maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
                                  //  maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
                                  //  maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
                                  //  maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
                                      maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
                                      maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
                                      maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
                                      maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
                                      maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
                                      maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
                                      maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
                                      maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
                                      maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
                                      maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
                                      maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
                                      maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
                                      maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
                                      maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
                                      maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
                                      maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
                                      maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
                                      maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
                                      maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
                                      maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
                                      maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
                                      maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
                                      maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
                                      maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
                                      maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
                                      maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
                                      maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
                                      maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
                                      maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
                                      maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
                                      maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
                                      maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
                                      maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
                                      maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
                                      maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
                                      maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
                                      maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
                                      maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
                                      maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
                                      maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
                                      maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
                                      maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
                                      maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
                                      maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
                                      maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
                                      maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
                                      maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
                                      maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
                                      maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
                                      maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
                                      maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
                                      maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
                                      maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
                                      maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
                                      maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
                                      maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
                                      maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
                                      maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
                                      maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
                                      maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
                                      maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
                                      maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
                                      maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
                                      maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
                                      maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
                                      maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
                                      maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
                                      maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
                                      maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
                                      maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
                                      maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
                                      maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
                                      maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
                                      maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
                                      maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
                                      maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
                                      maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
                                      maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
                                      maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
                                      maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
                                      maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
                                      maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
                                      maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
                                      maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
                                      maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
                                      maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
                                      maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
                                      maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
                                      maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
                                      maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
                                      maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
                                      maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
                                      maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
                                      maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
                                      maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
                                      maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
                                  }
                              
                                  /**
                                      @dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
                                      calculates the return for a given conversion (in the main token)
                              
                                      Formula:
                                      Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
                              
                                      @param _supply              token total supply
                                      @param _connectorBalance    total connector balance
                                      @param _connectorWeight     connector weight, represented in ppm, 1-1000000
                                      @param _depositAmount       deposit amount, in connector token
                              
                                      @return purchase return amount
                                  */
                                  function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {
                                      // validate input
                                      require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
                              
                                      // special case for 0 deposit amount
                                      if (_depositAmount == 0)
                                          return 0;
                              
                                      // special case if the weight = 100%
                                      if (_connectorWeight == MAX_WEIGHT)
                                          return safeMul(_supply, _depositAmount) / _connectorBalance;
                              
                                      uint256 result;
                                      uint8 precision;
                                      uint256 baseN = safeAdd(_depositAmount, _connectorBalance);
                                      (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
                                      uint256 temp = safeMul(_supply, result) >> precision;
                                      return temp - _supply;
                                  }
                              
                                  /**
                                      @dev given a token supply, connector balance, weight and a sell amount (in the main token),
                                      calculates the return for a given conversion (in the connector token)
                              
                                      Formula:
                                      Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
                              
                                      @param _supply              token total supply
                                      @param _connectorBalance    total connector
                                      @param _connectorWeight     constant connector Weight, represented in ppm, 1-1000000
                                      @param _sellAmount          sell amount, in the token itself
                              
                                      @return sale return amount
                                  */
                                  function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
                                      // validate input
                                      require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
                              
                                      // special case for 0 sell amount
                                      if (_sellAmount == 0)
                                          return 0;
                              
                                      // special case for selling the entire supply
                                      if (_sellAmount == _supply)
                                          return _connectorBalance;
                              
                                      // special case if the weight = 100%
                                      if (_connectorWeight == MAX_WEIGHT)
                                          return safeMul(_connectorBalance, _sellAmount) / _supply;
                              
                                      uint256 result;
                                      uint8 precision;
                                      uint256 baseD = _supply - _sellAmount;
                                      (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
                                      uint256 temp1 = safeMul(_connectorBalance, result);
                                      uint256 temp2 = _connectorBalance << precision;
                                      return (temp1 - temp2) / result;
                                  }
                              
                                  /**
                                      @dev given two connector balances/weights and a sell amount (in the first connector token),
                                      calculates the return for a conversion from the first connector token to the second connector token (in the second connector token)
                              
                                      Formula:
                                      Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight))
                              
                                      @param _fromConnectorBalance    input connector balance
                                      @param _fromConnectorWeight     input connector weight, represented in ppm, 1-1000000
                                      @param _toConnectorBalance      output connector balance
                                      @param _toConnectorWeight       output connector weight, represented in ppm, 1-1000000
                                      @param _amount                  input connector amount
                              
                                      @return second connector amount
                                  */
                                  function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) {
                                      // validate input
                                      require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT);
                              
                                      // special case for equal weights
                                      if (_fromConnectorWeight == _toConnectorWeight)
                                          return safeMul(_toConnectorBalance, _amount) / safeAdd(_fromConnectorBalance, _amount);
                              
                                      uint256 result;
                                      uint8 precision;
                                      uint256 baseN = safeAdd(_fromConnectorBalance, _amount);
                                      (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight);
                                      uint256 temp1 = safeMul(_toConnectorBalance, result);
                                      uint256 temp2 = _toConnectorBalance << precision;
                                      return (temp1 - temp2) / result;
                                  }
                              
                                  /**
                                      General Description:
                                          Determine a value of precision.
                                          Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
                                          Return the result along with the precision used.
                              
                                      Detailed Description:
                                          Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
                                          The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
                                          The larger "precision" is, the more accurately this value represents the real value.
                                          However, the larger "precision" is, the more bits are required in order to store this value.
                                          And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
                                          This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
                                          Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
                                          This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
                                          This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
                                  */
                                  function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
                                      assert(_baseN < MAX_NUM);
                              
                                      uint256 baseLog;
                                      uint256 base = _baseN * FIXED_1 / _baseD;
                                      if (base < OPT_LOG_MAX_VAL) {
                                          baseLog = optimalLog(base);
                                      }
                                      else {
                                          baseLog = generalLog(base);
                                      }
                              
                                      uint256 baseLogTimesExp = baseLog * _expN / _expD;
                                      if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
                                          return (optimalExp(baseLogTimesExp), MAX_PRECISION);
                                      }
                                      else {
                                          uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
                                          return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
                                      }
                                  }
                              
                                  /**
                                      Compute log(x / FIXED_1) * FIXED_1.
                                      This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
                                  */
                                  function generalLog(uint256 x) internal pure returns (uint256) {
                                      uint256 res = 0;
                              
                                      // If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
                                      if (x >= FIXED_2) {
                                          uint8 count = floorLog2(x / FIXED_1);
                                          x >>= count; // now x < 2
                                          res = count * FIXED_1;
                                      }
                              
                                      // If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
                                      if (x > FIXED_1) {
                                          for (uint8 i = MAX_PRECISION; i > 0; --i) {
                                              x = (x * x) / FIXED_1; // now 1 < x < 4
                                              if (x >= FIXED_2) {
                                                  x >>= 1; // now 1 < x < 2
                                                  res += ONE << (i - 1);
                                              }
                                          }
                                      }
                              
                                      return res * LN2_NUMERATOR / LN2_DENOMINATOR;
                                  }
                              
                                  /**
                                      Compute the largest integer smaller than or equal to the binary logarithm of the input.
                                  */
                                  function floorLog2(uint256 _n) internal pure returns (uint8) {
                                      uint8 res = 0;
                              
                                      if (_n < 256) {
                                          // At most 8 iterations
                                          while (_n > 1) {
                                              _n >>= 1;
                                              res += 1;
                                          }
                                      }
                                      else {
                                          // Exactly 8 iterations
                                          for (uint8 s = 128; s > 0; s >>= 1) {
                                              if (_n >= (ONE << s)) {
                                                  _n >>= s;
                                                  res |= s;
                                              }
                                          }
                                      }
                              
                                      return res;
                                  }
                              
                                  /**
                                      The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
                                      - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
                                      - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
                                  */
                                  function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
                                      uint8 lo = MIN_PRECISION;
                                      uint8 hi = MAX_PRECISION;
                              
                                      while (lo + 1 < hi) {
                                          uint8 mid = (lo + hi) / 2;
                                          if (maxExpArray[mid] >= _x)
                                              lo = mid;
                                          else
                                              hi = mid;
                                      }
                              
                                      if (maxExpArray[hi] >= _x)
                                          return hi;
                                      if (maxExpArray[lo] >= _x)
                                          return lo;
                              
                                      assert(false);
                                      return 0;
                                  }
                              
                                  /**
                                      This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
                                      It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
                                      It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
                                      The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
                                      The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
                                  */
                                  function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
                                      uint256 xi = _x;
                                      uint256 res = 0;
                              
                                      xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
                              
                                      return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
                                  }
                              
                                  /**
                                      Return log(x / FIXED_1) * FIXED_1
                                      Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1
                                      Auto-generated via 'PrintFunctionOptimalLog.py'
                                  */
                                  function optimalLog(uint256 x) internal pure returns (uint256) {
                                      uint256 res = 0;
                              
                                      uint256 y;
                                      uint256 z;
                                      uint256 w;
                              
                                      if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;}
                                      if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;}
                                      if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;}
                                      if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;}
                                      if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;}
                                      if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;}
                                      if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;}
                                      if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;}
                              
                                      z = y = x - FIXED_1;
                                      w = y * y / FIXED_1;
                                      res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1;
                                      res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1;
                                      res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1;
                                      res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1;
                                      res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1;
                                      res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1;
                                      res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1;
                                      res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000;
                              
                                      return res;
                                  }
                              
                                  /**
                                      Return e ^ (x / FIXED_1) * FIXED_1
                                      Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
                                      Auto-generated via 'PrintFunctionOptimalExp.py'
                                  */
                                  function optimalExp(uint256 x) internal pure returns (uint256) {
                                      uint256 res = 0;
                              
                                      uint256 y;
                                      uint256 z;
                              
                                      z = y = x % 0x10000000000000000000000000000000;
                                      z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
                                      z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
                                      z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
                                      z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
                                      z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
                                      z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
                                      z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
                                      z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
                                      z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
                                      z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
                                      z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
                                      z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
                                      z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
                                      z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
                                      z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
                                      z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
                                      z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
                                      z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
                                      z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
                                      res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
                              
                                      if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776;
                                      if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4;
                                      if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f;
                                      if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9;
                                      if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea;
                                      if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d;
                                      if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11;
                              
                                      return res;
                                  }
                              }

                              File 14 of 20: SmartToken
                              pragma solidity 0.4.26;
                              
                              // File: contracts/token/interfaces/IERC20Token.sol
                              
                              /*
                                  ERC20 Standard Token interface
                              */
                              contract IERC20Token {
                                  // these functions aren't abstract since the compiler emits automatically generated getter functions as external
                                  function name() public view returns (string) {this;}
                                  function symbol() public view returns (string) {this;}
                                  function decimals() public view returns (uint8) {this;}
                                  function totalSupply() public view returns (uint256) {this;}
                                  function balanceOf(address _owner) public view returns (uint256) {_owner; this;}
                                  function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;}
                              
                                  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);
                              }
                              
                              // File: contracts/utility/Utils.sol
                              
                              /**
                                * @dev Utilities & Common Modifiers
                              */
                              contract Utils {
                                  /**
                                    * constructor
                                  */
                                  constructor() public {
                                  }
                              
                                  // 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 != address(0));
                                      _;
                                  }
                              
                                  // verifies that the address is different than this contract address
                                  modifier notThis(address _address) {
                                      require(_address != address(this));
                                      _;
                                  }
                              
                              }
                              
                              // File: contracts/utility/SafeMath.sol
                              
                              /**
                                * @dev Library for basic math operations with overflow/underflow protection
                              */
                              library SafeMath {
                                  /**
                                    * @dev returns the sum of _x and _y, reverts if the calculation overflows
                                    * 
                                    * @param _x   value 1
                                    * @param _y   value 2
                                    * 
                                    * @return sum
                                  */
                                  function add(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      uint256 z = _x + _y;
                                      require(z >= _x);
                                      return z;
                                  }
                              
                                  /**
                                    * @dev returns the difference of _x minus _y, reverts if the calculation underflows
                                    * 
                                    * @param _x   minuend
                                    * @param _y   subtrahend
                                    * 
                                    * @return difference
                                  */
                                  function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      require(_x >= _y);
                                      return _x - _y;
                                  }
                              
                                  /**
                                    * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows
                                    * 
                                    * @param _x   factor 1
                                    * @param _y   factor 2
                                    * 
                                    * @return product
                                  */
                                  function mul(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      // gas optimization
                                      if (_x == 0)
                                          return 0;
                              
                                      uint256 z = _x * _y;
                                      require(z / _x == _y);
                                      return z;
                                  }
                              
                                    /**
                                      * ev Integer division of two numbers truncating the quotient, reverts on division by zero.
                                      * 
                                      * aram _x   dividend
                                      * aram _y   divisor
                                      * 
                                      * eturn quotient
                                  */
                                  function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      require(_y > 0);
                                      uint256 c = _x / _y;
                              
                                      return c;
                                  }
                              }
                              
                              // File: contracts/token/ERC20Token.sol
                              
                              /**
                                * @dev ERC20 Standard Token implementation
                              */
                              contract ERC20Token is IERC20Token, Utils {
                                  using SafeMath for uint256;
                              
                              
                                  string public name;
                                  string public symbol;
                                  uint8 public decimals;
                                  uint256 public totalSupply;
                                  mapping (address => uint256) public balanceOf;
                                  mapping (address => mapping (address => uint256)) public allowance;
                              
                                  /**
                                    * @dev triggered when tokens are transferred between wallets
                                    * 
                                    * @param _from    source address
                                    * @param _to      target address
                                    * @param _value   transfer amount
                                  */
                                  event Transfer(address indexed _from, address indexed _to, uint256 _value);
                              
                                  /**
                                    * @dev triggered when a wallet allows another wallet to transfer tokens from on its behalf
                                    * 
                                    * @param _owner   wallet that approves the allowance
                                    * @param _spender wallet that receives the allowance
                                    * @param _value   allowance amount
                                  */
                                  event Approval(address indexed _owner, address indexed _spender, uint256 _value);
                              
                                  /**
                                    * @dev initializes a new ERC20Token instance
                                    * 
                                    * @param _name        token name
                                    * @param _symbol      token symbol
                                    * @param _decimals    decimal points, for display purposes
                                    * @param _totalSupply total supply of token units
                                  */
                                  constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
                                      require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
                              
                                      name = _name;
                                      symbol = _symbol;
                                      decimals = _decimals;
                                      totalSupply = _totalSupply;
                                      balanceOf[msg.sender] = _totalSupply;
                                  }
                              
                                  /**
                                    * @dev send coins
                                    * throws on any error rather then return a false flag to minimize user errors
                                    * 
                                    * @param _to      target address
                                    * @param _value   transfer amount
                                    * 
                                    * @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transfer(address _to, uint256 _value)
                                      public
                                      validAddress(_to)
                                      returns (bool success)
                                  {
                                      balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
                                      balanceOf[_to] = balanceOf[_to].add(_value);
                                      emit Transfer(msg.sender, _to, _value);
                                      return true;
                                  }
                              
                                  /**
                                    * @dev an account/contract attempts to get the coins
                                    * throws on any error rather then return a false flag to minimize user errors
                                    * 
                                    * @param _from    source address
                                    * @param _to      target address
                                    * @param _value   transfer amount
                                    * 
                                    * @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transferFrom(address _from, address _to, uint256 _value)
                                      public
                                      validAddress(_from)
                                      validAddress(_to)
                                      returns (bool success)
                                  {
                                      allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
                                      balanceOf[_from] = balanceOf[_from].sub(_value);
                                      balanceOf[_to] = balanceOf[_to].add(_value);
                                      emit Transfer(_from, _to, _value);
                                      return true;
                                  }
                              
                                  /**
                                    * @dev allow another account/contract to spend some tokens on your behalf
                                    * throws on any error rather then return a false flag to minimize user errors
                                    * 
                                    * also, to minimize the risk of the approve/transferFrom attack vector
                                    * (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice
                                    * in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value
                                    * 
                                    * @param _spender approved address
                                    * @param _value   allowance amount
                                    * 
                                    * @return true if the approval was successful, false if it wasn't
                                  */
                                  function approve(address _spender, uint256 _value)
                                      public
                                      validAddress(_spender)
                                      returns (bool success)
                                  {
                                      // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
                                      require(_value == 0 || allowance[msg.sender][_spender] == 0);
                              
                                      allowance[msg.sender][_spender] = _value;
                                      emit Approval(msg.sender, _spender, _value);
                                      return true;
                                  }
                              }
                              
                              // File: contracts/utility/interfaces/IOwned.sol
                              
                              /*
                                  Owned contract interface
                              */
                              contract IOwned {
                                  // this function isn't abstract since the compiler emits automatically generated getter functions as external
                                  function owner() public view returns (address) {this;}
                              
                                  function transferOwnership(address _newOwner) public;
                                  function acceptOwnership() public;
                              }
                              
                              // File: contracts/token/interfaces/ISmartToken.sol
                              
                              /*
                                  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;
                              }
                              
                              // File: contracts/utility/Owned.sol
                              
                              /**
                                * @dev Provides support and utilities for contract ownership
                              */
                              contract Owned is IOwned {
                                  address public owner;
                                  address public newOwner;
                              
                                  /**
                                    * @dev triggered when the owner is updated
                                    * 
                                    * @param _prevOwner previous owner
                                    * @param _newOwner  new owner
                                  */
                                  event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
                              
                                  /**
                                    * @dev initializes a new Owned instance
                                  */
                                  constructor() public {
                                      owner = msg.sender;
                                  }
                              
                                  // allows execution by the owner only
                                  modifier ownerOnly {
                                      require(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);
                                      emit OwnerUpdate(owner, newOwner);
                                      owner = newOwner;
                                      newOwner = address(0);
                                  }
                              }
                              
                              // File: contracts/utility/interfaces/ITokenHolder.sol
                              
                              /*
                                  Token Holder interface
                              */
                              contract ITokenHolder is IOwned {
                                  function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
                              }
                              
                              // File: contracts/token/interfaces/INonStandardERC20.sol
                              
                              /*
                                  ERC20 Standard Token interface which doesn't return true/false for transfer, transferFrom and approve
                              */
                              contract INonStandardERC20 {
                                  // these functions aren't abstract since the compiler emits automatically generated getter functions as external
                                  function name() public view returns (string) {this;}
                                  function symbol() public view returns (string) {this;}
                                  function decimals() public view returns (uint8) {this;}
                                  function totalSupply() public view returns (uint256) {this;}
                                  function balanceOf(address _owner) public view returns (uint256) {_owner; this;}
                                  function allowance(address _owner, address _spender) public view returns (uint256) {_owner; _spender; this;}
                              
                                  function transfer(address _to, uint256 _value) public;
                                  function transferFrom(address _from, address _to, uint256 _value) public;
                                  function approve(address _spender, uint256 _value) public;
                              }
                              
                              // File: contracts/utility/TokenHolder.sol
                              
                              /**
                                * @dev 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.
                                * 
                                * Note that we use the non standard ERC-20 interface which has no return value for transfer
                                * in order to support both non standard as well as standard token contracts.
                                * see https://github.com/ethereum/solidity/issues/4116
                              */
                              contract TokenHolder is ITokenHolder, Owned, Utils {
                                  /**
                                    * @dev initializes a new TokenHolder instance
                                  */
                                  constructor() public {
                                  }
                              
                                  /**
                                    * @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)
                                  {
                                      INonStandardERC20(_token).transfer(_to, _amount);
                                  }
                              }
                              
                              // File: contracts/token/SmartToken.sol
                              
                              /**
                                * @dev Smart Token
                                * 
                                * 'Owned' is specified here for readability reasons
                              */
                              contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder {
                                  using SafeMath for uint256;
                              
                              
                                  string public version = '0.3';
                              
                                  bool public transfersEnabled = true;    // true if transfer/transferFrom are enabled, false if not
                              
                                  /**
                                    * @dev triggered when a smart token is deployed
                                    * the _token address is defined for forward compatibility, in case the event is trigger by a factory
                                    * 
                                    * @param _token  new smart token address
                                  */
                                  event NewSmartToken(address _token);
                              
                                  /**
                                    * @dev triggered when the total supply is increased
                                    * 
                                    * @param _amount  amount that gets added to the supply
                                  */
                                  event Issuance(uint256 _amount);
                              
                                  /**
                                    * @dev triggered when the total supply is decreased
                                    * 
                                    * @param _amount  amount that gets removed from the supply
                                  */
                                  event Destruction(uint256 _amount);
                              
                                  /**
                                    * @dev initializes a new SmartToken instance
                                    * 
                                    * @param _name       token name
                                    * @param _symbol     token short symbol, minimum 1 character
                                    * @param _decimals   for display purposes only
                                  */
                                  constructor(string _name, string _symbol, uint8 _decimals)
                                      public
                                      ERC20Token(_name, _symbol, _decimals, 0)
                                  {
                                      emit NewSmartToken(address(this));
                                  }
                              
                                  // allows execution only when transfers aren't disabled
                                  modifier transfersAllowed {
                                      assert(transfersEnabled);
                                      _;
                                  }
                              
                                  /**
                                    * @dev disables/enables transfers
                                    * can only be called by the contract owner
                                    * 
                                    * @param _disable    true to disable transfers, false to enable them
                                  */
                                  function disableTransfers(bool _disable) public ownerOnly {
                                      transfersEnabled = !_disable;
                                  }
                              
                                  /**
                                    * @dev increases the token supply and sends the new tokens to an account
                                    * can only be called by the contract owner
                                    * 
                                    * @param _to         account to receive the new amount
                                    * @param _amount     amount to increase the supply by
                                  */
                                  function issue(address _to, uint256 _amount)
                                      public
                                      ownerOnly
                                      validAddress(_to)
                                      notThis(_to)
                                  {
                                      totalSupply = totalSupply.add(_amount);
                                      balanceOf[_to] = balanceOf[_to].add(_amount);
                              
                                      emit Issuance(_amount);
                                      emit Transfer(this, _to, _amount);
                                  }
                              
                                  /**
                                    * @dev removes tokens from an account and decreases the token supply
                                    * can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account
                                    * 
                                    * @param _from       account to remove the amount from
                                    * @param _amount     amount to decrease the supply by
                                  */
                                  function destroy(address _from, uint256 _amount) public {
                                      require(msg.sender == _from || msg.sender == owner); // validate input
                              
                                      balanceOf[_from] = balanceOf[_from].sub(_amount);
                                      totalSupply = totalSupply.sub(_amount);
                              
                                      emit Transfer(_from, this, _amount);
                                      emit Destruction(_amount);
                                  }
                              
                                  // ERC20 standard method overrides with some extra functionality
                              
                                  /**
                                    * @dev send coins
                                    * throws on any error rather then return a false flag to minimize user errors
                                    * in addition to the standard checks, the function throws if transfers are disabled
                                    * 
                                    * @param _to      target address
                                    * @param _value   transfer amount
                                    * 
                                    * @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
                                      assert(super.transfer(_to, _value));
                                      return true;
                                  }
                              
                                  /**
                                    * @dev an account/contract attempts to get the coins
                                    * throws on any error rather then return a false flag to minimize user errors
                                    * in addition to the standard checks, the function throws if transfers are disabled
                                    * 
                                    * @param _from    source address
                                    * @param _to      target address
                                    * @param _value   transfer amount
                                    * 
                                    * @return true if the transfer was successful, false if it wasn't
                                  */
                                  function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
                                      assert(super.transferFrom(_from, _to, _value));
                                      return true;
                                  }
                              }
                              

                              File 15 of 20: ContractRegistry
                              pragma solidity ^0.4.24;
                              
                              // File: contracts/utility/interfaces/IOwned.sol
                              
                              /*
                                  Owned contract interface
                              */
                              contract IOwned {
                                  // this function isn't abstract since the compiler emits automatically generated getter functions as external
                                  function owner() public view returns (address) {}
                              
                                  function transferOwnership(address _newOwner) public;
                                  function acceptOwnership() public;
                              }
                              
                              // File: contracts/utility/Owned.sol
                              
                              /*
                                  Provides support and utilities for contract ownership
                              */
                              contract Owned is IOwned {
                                  address public owner;
                                  address public newOwner;
                              
                                  event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
                              
                                  /**
                                      @dev constructor
                                  */
                                  constructor() public {
                                      owner = msg.sender;
                                  }
                              
                                  // allows execution by the owner only
                                  modifier ownerOnly {
                                      require(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);
                                      emit OwnerUpdate(owner, newOwner);
                                      owner = newOwner;
                                      newOwner = address(0);
                                  }
                              }
                              
                              // File: contracts/utility/Utils.sol
                              
                              /*
                                  Utilities & Common Modifiers
                              */
                              contract Utils {
                                  /**
                                      constructor
                                  */
                                  constructor() public {
                                  }
                              
                                  // 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 != address(0));
                                      _;
                                  }
                              
                                  // 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 pure 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 pure 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 pure returns (uint256) {
                                      uint256 z = _x * _y;
                                      assert(_x == 0 || z / _x == _y);
                                      return z;
                                  }
                              }
                              
                              // File: contracts/utility/interfaces/IContractRegistry.sol
                              
                              /*
                                  Contract Registry interface
                              */
                              contract IContractRegistry {
                                  function addressOf(bytes32 _contractName) public view returns (address);
                              
                                  // deprecated, backward compatibility
                                  function getAddress(bytes32 _contractName) public view returns (address);
                              }
                              
                              // File: contracts/ContractIds.sol
                              
                              /**
                                  Id definitions for bancor contracts
                              
                                  Can be used in conjunction with the contract registry to get contract addresses
                              */
                              contract ContractIds {
                                  // generic
                                  bytes32 public constant CONTRACT_FEATURES = "ContractFeatures";
                                  bytes32 public constant CONTRACT_REGISTRY = "ContractRegistry";
                              
                                  // bancor logic
                                  bytes32 public constant BANCOR_NETWORK = "BancorNetwork";
                                  bytes32 public constant BANCOR_FORMULA = "BancorFormula";
                                  bytes32 public constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit";
                                  bytes32 public constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader";
                                  bytes32 public constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory";
                              
                                  // Ids of BNT converter and BNT token
                                  bytes32 public constant BNT_TOKEN = "BNTToken";
                                  bytes32 public constant BNT_CONVERTER = "BNTConverter";
                              
                                  // Id of BancorX contract
                                  bytes32 public constant BANCOR_X = "BancorX";
                              }
                              
                              // File: contracts/utility/ContractRegistry.sol
                              
                              /**
                                  Contract Registry
                              
                                  The contract registry keeps contract addresses by name.
                                  The owner can update contract addresses so that a contract name always points to the latest version
                                  of the given contract.
                                  Other contracts can query the registry to get updated addresses instead of depending on specific
                                  addresses.
                              
                                  Note that contract names are limited to 32 bytes UTF8 encoded ASCII strings to optimize gas costs
                              */
                              contract ContractRegistry is IContractRegistry, Owned, Utils, ContractIds {
                                  struct RegistryItem {
                                      address contractAddress;    // contract address
                                      uint256 nameIndex;          // index of the item in the list of contract names
                                      bool isSet;                 // used to tell if the mapping element is defined
                                  }
                              
                                  mapping (bytes32 => RegistryItem) private items;    // name -> RegistryItem mapping
                                  string[] public contractNames;                      // list of all registered contract names
                              
                                  // triggered when an address pointed to by a contract name is modified
                                  event AddressUpdate(bytes32 indexed _contractName, address _contractAddress);
                              
                                  /**
                                      @dev constructor
                                  */
                                  constructor() public {
                                      registerAddress(ContractIds.CONTRACT_REGISTRY, address(this));
                                  }
                              
                                  /**
                                      @dev returns the number of items in the registry
                              
                                      @return number of items
                                  */
                                  function itemCount() public view returns (uint256) {
                                      return contractNames.length;
                                  }
                              
                                  /**
                                      @dev returns the address associated with the given contract name
                              
                                      @param _contractName    contract name
                              
                                      @return contract address
                                  */
                                  function addressOf(bytes32 _contractName) public view returns (address) {
                                      return items[_contractName].contractAddress;
                                  }
                              
                                  /**
                                      @dev registers a new address for the contract name in the registry
                              
                                      @param _contractName     contract name
                                      @param _contractAddress  contract address
                                  */
                                  function registerAddress(bytes32 _contractName, address _contractAddress)
                                      public
                                      ownerOnly
                                      validAddress(_contractAddress)
                                  {
                                      require(_contractName.length > 0); // validate input
                              
                                      // update the address in the registry
                                      items[_contractName].contractAddress = _contractAddress;
                              
                                      if (!items[_contractName].isSet) {
                                          // mark the item as set
                                          items[_contractName].isSet = true;
                                          // add the contract name to the name list
                                          uint256 i = contractNames.push(bytes32ToString(_contractName));
                                          // update the item's index in the list
                                          items[_contractName].nameIndex = i - 1;
                                      }
                              
                                      // dispatch the address update event
                                      emit AddressUpdate(_contractName, _contractAddress);
                                  }
                              
                                  /**
                                      @dev removes an existing contract address from the registry
                              
                                      @param _contractName contract name
                                  */
                                  function unregisterAddress(bytes32 _contractName) public ownerOnly {
                                      require(_contractName.length > 0); // validate input
                              
                                      // remove the address from the registry
                                      items[_contractName].contractAddress = address(0);
                              
                                      // if there are multiple items in the registry, move the last element to the deleted element's position
                                      // and modify last element's registryItem.nameIndex in the items collection to point to the right position in contractNames
                                      if (contractNames.length > 1) {
                                          string memory lastContractNameString = contractNames[contractNames.length - 1];
                                          uint256 unregisterIndex = items[_contractName].nameIndex;
                              
                                          contractNames[unregisterIndex] = lastContractNameString;
                                          bytes32 lastContractName = stringToBytes32(lastContractNameString);
                                          RegistryItem storage registryItem = items[lastContractName];
                                          registryItem.nameIndex = unregisterIndex;
                                      }
                              
                                      // remove the last element from the name list
                                      contractNames.length--;
                                      // zero the deleted element's index
                                      items[_contractName].nameIndex = 0;
                              
                                      // dispatch the address update event
                                      emit AddressUpdate(_contractName, address(0));
                                  }
                              
                                  /**
                                      @dev utility, converts bytes32 to a string
                                      note that the bytes32 argument is assumed to be UTF8 encoded ASCII string
                              
                                      @return string representation of the given bytes32 argument
                                  */
                                  function bytes32ToString(bytes32 _bytes) private pure returns (string) {
                                      bytes memory byteArray = new bytes(32);
                                      for (uint256 i; i < 32; i++) {
                                          byteArray[i] = _bytes[i];
                                      }
                              
                                      return string(byteArray);
                                  }
                              
                                  // @dev utility, converts string to bytes32
                                  function stringToBytes32(string memory _string) private pure returns (bytes32) {
                                      bytes32 result;
                                      assembly {
                                          result := mload(add(_string,32))
                                      }
                                      return result;
                                  }
                              
                                  // deprecated, backward compatibility
                                  function getAddress(bytes32 _contractName) public view returns (address) {
                                      return addressOf(_contractName);
                                  }
                              }

                              File 16 of 20: BancorFormula
                              // File: contracts/converter/interfaces/IBancorFormula.sol
                              
                              pragma solidity 0.4.26;
                              
                              /*
                                  Bancor Formula interface
                              */
                              contract IBancorFormula {
                                  function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256);
                                  function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256);
                                  function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256);
                                  function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256);
                                  function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256);
                                  // deprecated, backward compatibility
                                  function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
                              }
                              
                              // File: contracts/utility/SafeMath.sol
                              
                              pragma solidity 0.4.26;
                              
                              /**
                                * @dev Library for basic math operations with overflow/underflow protection
                              */
                              library SafeMath {
                                  /**
                                    * @dev returns the sum of _x and _y, reverts if the calculation overflows
                                    * 
                                    * @param _x   value 1
                                    * @param _y   value 2
                                    * 
                                    * @return sum
                                  */
                                  function add(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      uint256 z = _x + _y;
                                      require(z >= _x);
                                      return z;
                                  }
                              
                                  /**
                                    * @dev returns the difference of _x minus _y, reverts if the calculation underflows
                                    * 
                                    * @param _x   minuend
                                    * @param _y   subtrahend
                                    * 
                                    * @return difference
                                  */
                                  function sub(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      require(_x >= _y);
                                      return _x - _y;
                                  }
                              
                                  /**
                                    * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows
                                    * 
                                    * @param _x   factor 1
                                    * @param _y   factor 2
                                    * 
                                    * @return product
                                  */
                                  function mul(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      // gas optimization
                                      if (_x == 0)
                                          return 0;
                              
                                      uint256 z = _x * _y;
                                      require(z / _x == _y);
                                      return z;
                                  }
                              
                                    /**
                                      * ev Integer division of two numbers truncating the quotient, reverts on division by zero.
                                      * 
                                      * aram _x   dividend
                                      * aram _y   divisor
                                      * 
                                      * eturn quotient
                                  */
                                  function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
                                      require(_y > 0);
                                      uint256 c = _x / _y;
                              
                                      return c;
                                  }
                              }
                              
                              // File: contracts/utility/Utils.sol
                              
                              pragma solidity 0.4.26;
                              
                              /**
                                * @dev Utilities & Common Modifiers
                              */
                              contract Utils {
                                  /**
                                    * constructor
                                  */
                                  constructor() public {
                                  }
                              
                                  // 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 != address(0));
                                      _;
                                  }
                              
                                  // verifies that the address is different than this contract address
                                  modifier notThis(address _address) {
                                      require(_address != address(this));
                                      _;
                                  }
                              
                              }
                              
                              // File: contracts/converter/BancorFormula.sol
                              
                              pragma solidity 0.4.26;
                              
                              
                              
                              
                              contract BancorFormula is IBancorFormula, Utils {
                                  using SafeMath for uint256;
                              
                                  uint16 public version = 5;
                              
                                  uint256 private constant ONE = 1;
                                  uint32 private constant MAX_RATIO = 1000000;
                                  uint8 private constant MIN_PRECISION = 32;
                                  uint8 private constant MAX_PRECISION = 127;
                              
                                  /**
                                    * Auto-generated via 'PrintIntScalingFactors.py'
                                  */
                                  uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
                                  uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
                                  uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
                              
                                  /**
                                    * Auto-generated via 'PrintLn2ScalingFactors.py'
                                  */
                                  uint256 private constant LN2_NUMERATOR   = 0x3f80fe03f80fe03f80fe03f80fe03f8;
                                  uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
                              
                                  /**
                                    * Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
                                  */
                                  uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
                                  uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
                              
                                  /**
                                    * Auto-generated via 'PrintFunctionConstructor.py'
                                  */
                                  uint256[128] private maxExpArray;
                                  constructor() public {
                                  //  maxExpArray[  0] = 0x6bffffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  1] = 0x67ffffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  2] = 0x637fffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  3] = 0x5f6fffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  4] = 0x5b77ffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  5] = 0x57b3ffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  6] = 0x5419ffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  7] = 0x50a2ffffffffffffffffffffffffffffff;
                                  //  maxExpArray[  8] = 0x4d517fffffffffffffffffffffffffffff;
                                  //  maxExpArray[  9] = 0x4a233fffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
                                  //  maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
                                  //  maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
                                  //  maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
                                  //  maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
                                  //  maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
                                  //  maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
                                  //  maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
                                  //  maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
                                  //  maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
                                  //  maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
                                      maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
                                      maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
                                      maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
                                      maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
                                      maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
                                      maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
                                      maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
                                      maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
                                      maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
                                      maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
                                      maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
                                      maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
                                      maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
                                      maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
                                      maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
                                      maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
                                      maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
                                      maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
                                      maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
                                      maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
                                      maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
                                      maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
                                      maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
                                      maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
                                      maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
                                      maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
                                      maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
                                      maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
                                      maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
                                      maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
                                      maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
                                      maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
                                      maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
                                      maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
                                      maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
                                      maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
                                      maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
                                      maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
                                      maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
                                      maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
                                      maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
                                      maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
                                      maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
                                      maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
                                      maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
                                      maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
                                      maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
                                      maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
                                      maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
                                      maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
                                      maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
                                      maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
                                      maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
                                      maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
                                      maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
                                      maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
                                      maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
                                      maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
                                      maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
                                      maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
                                      maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
                                      maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
                                      maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
                                      maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
                                      maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
                                      maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
                                      maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
                                      maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
                                      maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
                                      maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
                                      maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
                                      maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
                                      maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
                                      maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
                                      maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
                                      maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
                                      maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
                                      maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
                                      maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
                                      maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
                                      maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
                                      maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
                                      maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
                                      maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
                                      maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
                                      maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
                                      maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
                                      maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
                                      maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
                                      maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
                                      maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
                                      maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
                                      maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
                                      maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
                                      maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
                                      maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
                                  }
                              
                                  /**
                                    * @dev given a token supply, reserve balance, ratio and a deposit amount (in the reserve token),
                                    * calculates the return for a given conversion (in the main token)
                                    * 
                                    * Formula:
                                    * Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 1000000) - 1)
                                    * 
                                    * @param _supply              token total supply
                                    * @param _reserveBalance      total reserve balance
                                    * @param _reserveRatio        reserve ratio, represented in ppm, 1-1000000
                                    * @param _depositAmount       deposit amount, in reserve token
                                    * 
                                    * @return purchase return amount
                                  */
                                  function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) public view returns (uint256) {
                                      // validate input
                                      require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RATIO);
                              
                                      // special case for 0 deposit amount
                                      if (_depositAmount == 0)
                                          return 0;
                              
                                      // special case if the ratio = 100%
                                      if (_reserveRatio == MAX_RATIO)
                                          return _supply.mul(_depositAmount) / _reserveBalance;
                              
                                      uint256 result;
                                      uint8 precision;
                                      uint256 baseN = _depositAmount.add(_reserveBalance);
                                      (result, precision) = power(baseN, _reserveBalance, _reserveRatio, MAX_RATIO);
                                      uint256 temp = _supply.mul(result) >> precision;
                                      return temp - _supply;
                                  }
                              
                                  /**
                                    * @dev given a token supply, reserve balance, ratio and a sell amount (in the main token),
                                    * calculates the return for a given conversion (in the reserve token)
                                    * 
                                    * Formula:
                                    * Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / 1000000)))
                                    * 
                                    * @param _supply              token total supply
                                    * @param _reserveBalance      total reserve
                                    * @param _reserveRatio        constant reserve Ratio, represented in ppm, 1-1000000
                                    * @param _sellAmount          sell amount, in the token itself
                                    * 
                                    * @return sale return amount
                                  */
                                  function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) public view returns (uint256) {
                                      // validate input
                                      require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RATIO && _sellAmount <= _supply);
                              
                                      // special case for 0 sell amount
                                      if (_sellAmount == 0)
                                          return 0;
                              
                                      // special case for selling the entire supply
                                      if (_sellAmount == _supply)
                                          return _reserveBalance;
                              
                                      // special case if the ratio = 100%
                                      if (_reserveRatio == MAX_RATIO)
                                          return _reserveBalance.mul(_sellAmount) / _supply;
                              
                                      uint256 result;
                                      uint8 precision;
                                      uint256 baseD = _supply - _sellAmount;
                                      (result, precision) = power(_supply, baseD, MAX_RATIO, _reserveRatio);
                                      uint256 temp1 = _reserveBalance.mul(result);
                                      uint256 temp2 = _reserveBalance << precision;
                                      return (temp1 - temp2) / result;
                                  }
                              
                                  /**
                                    * @dev given two reserve balances/ratios and a sell amount (in the first reserve token),
                                    * calculates the return for a conversion from the first reserve token to the second reserve token (in the second reserve token)
                                    * note that prior to version 4, you should use 'calculateCrossConnectorReturn' instead
                                    * 
                                    * Formula:
                                    * Return = _toReserveBalance * (1 - (_fromReserveBalance / (_fromReserveBalance + _amount)) ^ (_fromReserveRatio / _toReserveRatio))
                                    * 
                                    * @param _fromReserveBalance      input reserve balance
                                    * @param _fromReserveRatio        input reserve ratio, represented in ppm, 1-1000000
                                    * @param _toReserveBalance        output reserve balance
                                    * @param _toReserveRatio          output reserve ratio, represented in ppm, 1-1000000
                                    * @param _amount                  input reserve amount
                                    * 
                                    * @return second reserve amount
                                  */
                                  function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) public view returns (uint256) {
                                      // validate input
                                      require(_fromReserveBalance > 0 && _fromReserveRatio > 0 && _fromReserveRatio <= MAX_RATIO && _toReserveBalance > 0 && _toReserveRatio > 0 && _toReserveRatio <= MAX_RATIO);
                              
                                      // special case for equal ratios
                                      if (_fromReserveRatio == _toReserveRatio)
                                          return _toReserveBalance.mul(_amount) / _fromReserveBalance.add(_amount);
                              
                                      uint256 result;
                                      uint8 precision;
                                      uint256 baseN = _fromReserveBalance.add(_amount);
                                      (result, precision) = power(baseN, _fromReserveBalance, _fromReserveRatio, _toReserveRatio);
                                      uint256 temp1 = _toReserveBalance.mul(result);
                                      uint256 temp2 = _toReserveBalance << precision;
                                      return (temp1 - temp2) / result;
                                  }
                              
                                  /**
                                    * @dev given a smart token supply, reserve balance, total ratio and an amount of requested smart tokens,
                                    * calculates the amount of reserve tokens required for purchasing the given amount of smart tokens
                                    * 
                                    * Formula:
                                    * Return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_RATIO / _totalRatio) - 1)
                                    * 
                                    * @param _supply              smart token supply
                                    * @param _reserveBalance      reserve token balance
                                    * @param _totalRatio          total ratio, represented in ppm, 2-2000000
                                    * @param _amount              requested amount of smart tokens
                                    * 
                                    * @return amount of reserve tokens
                                  */
                                  function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256) {
                                      // validate input
                                      require(_supply > 0 && _reserveBalance > 0 && _totalRatio > 1 && _totalRatio <= MAX_RATIO * 2);
                              
                                      // special case for 0 amount
                                      if (_amount == 0)
                                          return 0;
                              
                                      // special case if the total ratio = 100%
                                      if (_totalRatio == MAX_RATIO)
                                          return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
                              
                                      uint256 result;
                                      uint8 precision;
                                      uint256 baseN = _supply.add(_amount);
                                      (result, precision) = power(baseN, _supply, MAX_RATIO, _totalRatio);
                                      uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1;
                                      return temp - _reserveBalance;
                                  }
                              
                                  /**
                                    * @dev given a smart token supply, reserve balance, total ratio and an amount of smart tokens to liquidate,
                                    * calculates the amount of reserve tokens received for selling the given amount of smart tokens
                                    * 
                                    * Formula:
                                    * Return = _reserveBalance * ((_supply / (_supply - _amount)) ^ (MAX_RATIO / _totalRatio) - 1)
                                    * 
                                    * @param _supply              smart token supply
                                    * @param _reserveBalance      reserve token balance
                                    * @param _totalRatio          total ratio, represented in ppm, 2-2000000
                                    * @param _amount              amount of smart tokens to liquidate
                                    * 
                                    * @return amount of reserve tokens
                                  */
                                  function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) public view returns (uint256) {
                                      // validate input
                                      require(_supply > 0 && _reserveBalance > 0 && _totalRatio > 1 && _totalRatio <= MAX_RATIO * 2 && _amount <= _supply);
                              
                                      // special case for 0 amount
                                      if (_amount == 0)
                                          return 0;
                              
                                      // special case if the total ratio = 100%
                                      if (_totalRatio == MAX_RATIO)
                                          return _amount.mul(_reserveBalance) / _supply;
                              
                                      uint256 result;
                                      uint8 precision;
                                      uint256 baseD = _supply - _amount;
                                      (result, precision) = power(_supply, baseD, MAX_RATIO, _totalRatio);
                                      uint256 temp = _reserveBalance.mul(result) >> precision;
                                      return temp - _reserveBalance;
                                  }
                              
                                  /**
                                    * @dev General Description:
                                    *     Determine a value of precision.
                                    *     Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
                                    *     Return the result along with the precision used.
                                    * 
                                    * Detailed Description:
                                    *     Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
                                    *     The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
                                    *     The larger "precision" is, the more accurately this value represents the real value.
                                    *     However, the larger "precision" is, the more bits are required in order to store this value.
                                    *     And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
                                    *     This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
                                    *     Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
                                    *     This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
                                    *     This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
                                  */
                                  function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
                                      require(_baseN < MAX_NUM);
                              
                                      uint256 baseLog;
                                      uint256 base = _baseN * FIXED_1 / _baseD;
                                      if (base < OPT_LOG_MAX_VAL) {
                                          baseLog = optimalLog(base);
                                      }
                                      else {
                                          baseLog = generalLog(base);
                                      }
                              
                                      uint256 baseLogTimesExp = baseLog * _expN / _expD;
                                      if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
                                          return (optimalExp(baseLogTimesExp), MAX_PRECISION);
                                      }
                                      else {
                                          uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
                                          return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
                                      }
                                  }
                              
                                  /**
                                    * @dev computes log(x / FIXED_1) * FIXED_1.
                                    * This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
                                  */
                                  function generalLog(uint256 x) internal pure returns (uint256) {
                                      uint256 res = 0;
                              
                                      // If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
                                      if (x >= FIXED_2) {
                                          uint8 count = floorLog2(x / FIXED_1);
                                          x >>= count; // now x < 2
                                          res = count * FIXED_1;
                                      }
                              
                                      // If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
                                      if (x > FIXED_1) {
                                          for (uint8 i = MAX_PRECISION; i > 0; --i) {
                                              x = (x * x) / FIXED_1; // now 1 < x < 4
                                              if (x >= FIXED_2) {
                                                  x >>= 1; // now 1 < x < 2
                                                  res += ONE << (i - 1);
                                              }
                                          }
                                      }
                              
                                      return res * LN2_NUMERATOR / LN2_DENOMINATOR;
                                  }
                              
                                  /**
                                    * @dev computes the largest integer smaller than or equal to the binary logarithm of the input.
                                  */
                                  function floorLog2(uint256 _n) internal pure returns (uint8) {
                                      uint8 res = 0;
                              
                                      if (_n < 256) {
                                          // At most 8 iterations
                                          while (_n > 1) {
                                              _n >>= 1;
                                              res += 1;
                                          }
                                      }
                                      else {
                                          // Exactly 8 iterations
                                          for (uint8 s = 128; s > 0; s >>= 1) {
                                              if (_n >= (ONE << s)) {
                                                  _n >>= s;
                                                  res |= s;
                                              }
                                          }
                                      }
                              
                                      return res;
                                  }
                              
                                  /**
                                    * @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
                                    * - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
                                    * - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
                                  */
                                  function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
                                      uint8 lo = MIN_PRECISION;
                                      uint8 hi = MAX_PRECISION;
                              
                                      while (lo + 1 < hi) {
                                          uint8 mid = (lo + hi) / 2;
                                          if (maxExpArray[mid] >= _x)
                                              lo = mid;
                                          else
                                              hi = mid;
                                      }
                              
                                      if (maxExpArray[hi] >= _x)
                                          return hi;
                                      if (maxExpArray[lo] >= _x)
                                          return lo;
                              
                                      require(false);
                                      return 0;
                                  }
                              
                                  /**
                                    * @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
                                    * it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
                                    * it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
                                    * the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
                                    * the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
                                  */
                                  function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
                                      uint256 xi = _x;
                                      uint256 res = 0;
                              
                                      xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
                                      xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
                              
                                      return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
                                  }
                              
                                  /**
                                    * @dev computes log(x / FIXED_1) * FIXED_1
                                    * Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1
                                    * Auto-generated via 'PrintFunctionOptimalLog.py'
                                    * Detailed description:
                                    * - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
                                    * - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
                                    * - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
                                    * - The natural logarithm of the input is calculated by summing up the intermediate results above
                                    * - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
                                  */
                                  function optimalLog(uint256 x) internal pure returns (uint256) {
                                      uint256 res = 0;
                              
                                      uint256 y;
                                      uint256 z;
                                      uint256 w;
                              
                                      if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1
                                      if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2
                                      if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3
                                      if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4
                                      if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5
                                      if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6
                                      if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7
                                      if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8
                              
                                      z = y = x - FIXED_1;
                                      w = y * y / FIXED_1;
                                      res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
                                      res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
                                      res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
                                      res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
                                      res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
                                      res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
                                      res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
                                      res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000;                      // add y^15 / 15 - y^16 / 16
                              
                                      return res;
                                  }
                              
                                  /**
                                    * @dev computes e ^ (x / FIXED_1) * FIXED_1
                                    * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
                                    * auto-generated via 'PrintFunctionOptimalExp.py'
                                    * Detailed description:
                                    * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
                                    * - The exponentiation of each binary exponent is given (pre-calculated)
                                    * - The exponentiation of r is calculated via Taylor series for e^x, where x = r
                                    * - The exponentiation of the input is calculated by multiplying the intermediate results above
                                    * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
                                  */
                                  function optimalExp(uint256 x) internal pure returns (uint256) {
                                      uint256 res = 0;
                              
                                      uint256 y;
                                      uint256 z;
                              
                                      z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
                                      z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
                                      z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
                                      z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
                                      z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
                                      z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
                                      z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
                                      z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
                                      z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
                                      z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
                                      z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
                                      z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
                                      z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
                                      z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
                                      z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
                                      z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
                                      z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
                                      z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
                                      z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
                                      z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
                                      res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
                              
                                      if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
                                      if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
                                      if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
                                      if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
                                      if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
                                      if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
                                      if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
                              
                                      return res;
                                  }
                              
                                  /**
                                    * @dev deprecated, backward compatibility
                                  */
                                  function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) {
                                      return calculateCrossReserveReturn(_fromConnectorBalance, _fromConnectorWeight, _toConnectorBalance, _toConnectorWeight, _amount);
                                  }
                              }

                              File 17 of 20: ConversionRates
                              pragma solidity 0.4.18;
                              
                              interface ConversionRatesInterface {
                              
                                  function recordImbalance(
                                      ERC20 token,
                                      int buyAmount,
                                      uint rateUpdateBlock,
                                      uint currentBlock
                                  )
                                      public;
                              
                                  function getRate(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint);
                              }
                              
                              interface ERC20 {
                                  function totalSupply() public view returns (uint supply);
                                  function balanceOf(address _owner) public view returns (uint balance);
                                  function transfer(address _to, uint _value) public returns (bool success);
                                  function transferFrom(address _from, address _to, uint _value) public returns (bool success);
                                  function approve(address _spender, uint _value) public returns (bool success);
                                  function allowance(address _owner, address _spender) public view returns (uint remaining);
                                  function decimals() public view returns(uint digits);
                                  event Approval(address indexed _owner, address indexed _spender, uint _value);
                              }
                              
                              contract PermissionGroups {
                              
                                  address public admin;
                                  address public pendingAdmin;
                                  mapping(address=>bool) internal operators;
                                  mapping(address=>bool) internal alerters;
                                  address[] internal operatorsGroup;
                                  address[] internal alertersGroup;
                                  uint constant internal MAX_GROUP_SIZE = 50;
                              
                                  function PermissionGroups() public {
                                      admin = msg.sender;
                                  }
                              
                                  modifier onlyAdmin() {
                                      require(msg.sender == admin);
                                      _;
                                  }
                              
                                  modifier onlyOperator() {
                                      require(operators[msg.sender]);
                                      _;
                                  }
                              
                                  modifier onlyAlerter() {
                                      require(alerters[msg.sender]);
                                      _;
                                  }
                              
                                  function getOperators () external view returns(address[]) {
                                      return operatorsGroup;
                                  }
                              
                                  function getAlerters () external view returns(address[]) {
                                      return alertersGroup;
                                  }
                              
                                  event TransferAdminPending(address pendingAdmin);
                              
                                  /**
                                   * @dev Allows the current admin to set the pendingAdmin address.
                                   * @param newAdmin The address to transfer ownership to.
                                   */
                                  function transferAdmin(address newAdmin) public onlyAdmin {
                                      require(newAdmin != address(0));
                                      TransferAdminPending(pendingAdmin);
                                      pendingAdmin = newAdmin;
                                  }
                              
                                  /**
                                   * @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
                                   * @param newAdmin The address to transfer ownership to.
                                   */
                                  function transferAdminQuickly(address newAdmin) public onlyAdmin {
                                      require(newAdmin != address(0));
                                      TransferAdminPending(newAdmin);
                                      AdminClaimed(newAdmin, admin);
                                      admin = newAdmin;
                                  }
                              
                                  event AdminClaimed( address newAdmin, address previousAdmin);
                              
                                  /**
                                   * @dev Allows the pendingAdmin address to finalize the change admin process.
                                   */
                                  function claimAdmin() public {
                                      require(pendingAdmin == msg.sender);
                                      AdminClaimed(pendingAdmin, admin);
                                      admin = pendingAdmin;
                                      pendingAdmin = address(0);
                                  }
                              
                                  event AlerterAdded (address newAlerter, bool isAdd);
                              
                                  function addAlerter(address newAlerter) public onlyAdmin {
                                      require(!alerters[newAlerter]); // prevent duplicates.
                                      require(alertersGroup.length < MAX_GROUP_SIZE);
                              
                                      AlerterAdded(newAlerter, true);
                                      alerters[newAlerter] = true;
                                      alertersGroup.push(newAlerter);
                                  }
                              
                                  function removeAlerter (address alerter) public onlyAdmin {
                                      require(alerters[alerter]);
                                      alerters[alerter] = false;
                              
                                      for (uint i = 0; i < alertersGroup.length; ++i) {
                                          if (alertersGroup[i] == alerter) {
                                              alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
                                              alertersGroup.length--;
                                              AlerterAdded(alerter, false);
                                              break;
                                          }
                                      }
                                  }
                              
                                  event OperatorAdded(address newOperator, bool isAdd);
                              
                                  function addOperator(address newOperator) public onlyAdmin {
                                      require(!operators[newOperator]); // prevent duplicates.
                                      require(operatorsGroup.length < MAX_GROUP_SIZE);
                              
                                      OperatorAdded(newOperator, true);
                                      operators[newOperator] = true;
                                      operatorsGroup.push(newOperator);
                                  }
                              
                                  function removeOperator (address operator) public onlyAdmin {
                                      require(operators[operator]);
                                      operators[operator] = false;
                              
                                      for (uint i = 0; i < operatorsGroup.length; ++i) {
                                          if (operatorsGroup[i] == operator) {
                                              operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
                                              operatorsGroup.length -= 1;
                                              OperatorAdded(operator, false);
                                              break;
                                          }
                                      }
                                  }
                              }
                              
                              contract Withdrawable is PermissionGroups {
                              
                                  event TokenWithdraw(ERC20 token, uint amount, address sendTo);
                              
                                  /**
                                   * @dev Withdraw all ERC20 compatible tokens
                                   * @param token ERC20 The address of the token contract
                                   */
                                  function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
                                      require(token.transfer(sendTo, amount));
                                      TokenWithdraw(token, amount, sendTo);
                                  }
                              
                                  event EtherWithdraw(uint amount, address sendTo);
                              
                                  /**
                                   * @dev Withdraw Ethers
                                   */
                                  function withdrawEther(uint amount, address sendTo) external onlyAdmin {
                                      sendTo.transfer(amount);
                                      EtherWithdraw(amount, sendTo);
                                  }
                              }
                              
                              contract VolumeImbalanceRecorder is Withdrawable {
                              
                                  uint constant internal SLIDING_WINDOW_SIZE = 5;
                                  uint constant internal POW_2_64 = 2 ** 64;
                              
                                  struct TokenControlInfo {
                                      uint minimalRecordResolution; // can be roughly 1 cent
                                      uint maxPerBlockImbalance; // in twei resolution
                                      uint maxTotalImbalance; // max total imbalance (between rate updates)
                                                          // before halting trade
                                  }
                              
                                  mapping(address => TokenControlInfo) internal tokenControlInfo;
                              
                                  struct TokenImbalanceData {
                                      int  lastBlockBuyUnitsImbalance;
                                      uint lastBlock;
                              
                                      int  totalBuyUnitsImbalance;
                                      uint lastRateUpdateBlock;
                                  }
                              
                                  mapping(address => mapping(uint=>uint)) public tokenImbalanceData;
                              
                                  function VolumeImbalanceRecorder(address _admin) public {
                                      require(_admin != address(0));
                                      admin = _admin;
                                  }
                              
                                  function setTokenControlInfo(
                                      ERC20 token,
                                      uint minimalRecordResolution,
                                      uint maxPerBlockImbalance,
                                      uint maxTotalImbalance
                                  )
                                      public
                                      onlyAdmin
                                  {
                                      tokenControlInfo[token] =
                                          TokenControlInfo(
                                              minimalRecordResolution,
                                              maxPerBlockImbalance,
                                              maxTotalImbalance
                                          );
                                  }
                              
                                  function getTokenControlInfo(ERC20 token) public view returns(uint, uint, uint) {
                                      return (tokenControlInfo[token].minimalRecordResolution,
                                              tokenControlInfo[token].maxPerBlockImbalance,
                                              tokenControlInfo[token].maxTotalImbalance);
                                  }
                              
                                  function addImbalance(
                                      ERC20 token,
                                      int buyAmount,
                                      uint rateUpdateBlock,
                                      uint currentBlock
                                  )
                                      internal
                                  {
                                      uint currentBlockIndex = currentBlock % SLIDING_WINDOW_SIZE;
                                      int recordedBuyAmount = int(buyAmount / int(tokenControlInfo[token].minimalRecordResolution));
                              
                                      int prevImbalance = 0;
                              
                                      TokenImbalanceData memory currentBlockData =
                                          decodeTokenImbalanceData(tokenImbalanceData[token][currentBlockIndex]);
                              
                                      // first scenario - this is not the first tx in the current block
                                      if (currentBlockData.lastBlock == currentBlock) {
                                          if (uint(currentBlockData.lastRateUpdateBlock) == rateUpdateBlock) {
                                              // just increase imbalance
                                              currentBlockData.lastBlockBuyUnitsImbalance += recordedBuyAmount;
                                              currentBlockData.totalBuyUnitsImbalance += recordedBuyAmount;
                                          } else {
                                              // imbalance was changed in the middle of the block
                                              prevImbalance = getImbalanceInRange(token, rateUpdateBlock, currentBlock);
                                              currentBlockData.totalBuyUnitsImbalance = int(prevImbalance) + recordedBuyAmount;
                                              currentBlockData.lastBlockBuyUnitsImbalance += recordedBuyAmount;
                                              currentBlockData.lastRateUpdateBlock = uint(rateUpdateBlock);
                                          }
                                      } else {
                                          // first tx in the current block
                                          int currentBlockImbalance;
                                          (prevImbalance, currentBlockImbalance) = getImbalanceSinceRateUpdate(token, rateUpdateBlock, currentBlock);
                              
                                          currentBlockData.lastBlockBuyUnitsImbalance = recordedBuyAmount;
                                          currentBlockData.lastBlock = uint(currentBlock);
                                          currentBlockData.lastRateUpdateBlock = uint(rateUpdateBlock);
                                          currentBlockData.totalBuyUnitsImbalance = int(prevImbalance) + recordedBuyAmount;
                                      }
                              
                                      tokenImbalanceData[token][currentBlockIndex] = encodeTokenImbalanceData(currentBlockData);
                                  }
                              
                                  function setGarbageToVolumeRecorder(ERC20 token) internal {
                                      for (uint i = 0; i < SLIDING_WINDOW_SIZE; i++) {
                                          tokenImbalanceData[token][i] = 0x1;
                                      }
                                  }
                              
                                  function getImbalanceInRange(ERC20 token, uint startBlock, uint endBlock) internal view returns(int buyImbalance) {
                                      // check the imbalance in the sliding window
                                      require(startBlock <= endBlock);
                              
                                      buyImbalance = 0;
                              
                                      for (uint windowInd = 0; windowInd < SLIDING_WINDOW_SIZE; windowInd++) {
                                          TokenImbalanceData memory perBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][windowInd]);
                              
                                          if (perBlockData.lastBlock <= endBlock && perBlockData.lastBlock >= startBlock) {
                                              buyImbalance += int(perBlockData.lastBlockBuyUnitsImbalance);
                                          }
                                      }
                                  }
                              
                                  function getImbalanceSinceRateUpdate(ERC20 token, uint rateUpdateBlock, uint currentBlock)
                                      internal view
                                      returns(int buyImbalance, int currentBlockImbalance)
                                  {
                                      buyImbalance = 0;
                                      currentBlockImbalance = 0;
                                      uint latestBlock = 0;
                                      int imbalanceInRange = 0;
                                      uint startBlock = rateUpdateBlock;
                                      uint endBlock = currentBlock;
                              
                                      for (uint windowInd = 0; windowInd < SLIDING_WINDOW_SIZE; windowInd++) {
                                          TokenImbalanceData memory perBlockData = decodeTokenImbalanceData(tokenImbalanceData[token][windowInd]);
                              
                                          if (perBlockData.lastBlock <= endBlock && perBlockData.lastBlock >= startBlock) {
                                              imbalanceInRange += perBlockData.lastBlockBuyUnitsImbalance;
                                          }
                              
                                          if (perBlockData.lastRateUpdateBlock != rateUpdateBlock) continue;
                                          if (perBlockData.lastBlock < latestBlock) continue;
                              
                                          latestBlock = perBlockData.lastBlock;
                                          buyImbalance = perBlockData.totalBuyUnitsImbalance;
                                          if (uint(perBlockData.lastBlock) == currentBlock) {
                                              currentBlockImbalance = perBlockData.lastBlockBuyUnitsImbalance;
                                          }
                                      }
                              
                                      if (buyImbalance == 0) {
                                          buyImbalance = imbalanceInRange;
                                      }
                                  }
                              
                                  function getImbalance(ERC20 token, uint rateUpdateBlock, uint currentBlock)
                                      internal view
                                      returns(int totalImbalance, int currentBlockImbalance)
                                  {
                              
                                      int resolution = int(tokenControlInfo[token].minimalRecordResolution);
                              
                                      (totalImbalance, currentBlockImbalance) =
                                          getImbalanceSinceRateUpdate(
                                              token,
                                              rateUpdateBlock,
                                              currentBlock);
                              
                                      totalImbalance *= resolution;
                                      currentBlockImbalance *= resolution;
                                  }
                              
                                  function getMaxPerBlockImbalance(ERC20 token) internal view returns(uint) {
                                      return tokenControlInfo[token].maxPerBlockImbalance;
                                  }
                              
                                  function getMaxTotalImbalance(ERC20 token) internal view returns(uint) {
                                      return tokenControlInfo[token].maxTotalImbalance;
                                  }
                              
                                  function encodeTokenImbalanceData(TokenImbalanceData data) internal pure returns(uint) {
                                      // check for overflows
                                      require(data.lastBlockBuyUnitsImbalance < int(POW_2_64 / 2));
                                      require(data.lastBlockBuyUnitsImbalance > int(-1 * int(POW_2_64) / 2));
                                      require(data.lastBlock < POW_2_64);
                                      require(data.totalBuyUnitsImbalance < int(POW_2_64 / 2));
                                      require(data.totalBuyUnitsImbalance > int(-1 * int(POW_2_64) / 2));
                                      require(data.lastRateUpdateBlock < POW_2_64);
                              
                                      // do encoding
                                      uint result = uint(data.lastBlockBuyUnitsImbalance) & (POW_2_64 - 1);
                                      result |= data.lastBlock * POW_2_64;
                                      result |= (uint(data.totalBuyUnitsImbalance) & (POW_2_64 - 1)) * POW_2_64 * POW_2_64;
                                      result |= data.lastRateUpdateBlock * POW_2_64 * POW_2_64 * POW_2_64;
                              
                                      return result;
                                  }
                              
                                  function decodeTokenImbalanceData(uint input) internal pure returns(TokenImbalanceData) {
                                      TokenImbalanceData memory data;
                              
                                      data.lastBlockBuyUnitsImbalance = int(int64(input & (POW_2_64 - 1)));
                                      data.lastBlock = uint(uint64((input / POW_2_64) & (POW_2_64 - 1)));
                                      data.totalBuyUnitsImbalance = int(int64((input / (POW_2_64 * POW_2_64)) & (POW_2_64 - 1)));
                                      data.lastRateUpdateBlock = uint(uint64((input / (POW_2_64 * POW_2_64 * POW_2_64))));
                              
                                      return data;
                                  }
                              }
                              
                              contract Utils {
                              
                                  ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
                                  uint  constant internal PRECISION = (10**18);
                                  uint  constant internal MAX_QTY   = (10**28); // 10B tokens
                                  uint  constant internal MAX_RATE  = (PRECISION * 10**6); // up to 1M tokens per ETH
                                  uint  constant internal MAX_DECIMALS = 18;
                                  uint  constant internal ETH_DECIMALS = 18;
                                  mapping(address=>uint) internal decimals;
                              
                                  function setDecimals(ERC20 token) internal {
                                      if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
                                      else decimals[token] = token.decimals();
                                  }
                              
                                  function getDecimals(ERC20 token) internal view returns(uint) {
                                      if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
                                      uint tokenDecimals = decimals[token];
                                      // technically, there might be token with decimals 0
                                      // moreover, very possible that old tokens have decimals 0
                                      // these tokens will just have higher gas fees.
                                      if(tokenDecimals == 0) return token.decimals();
                              
                                      return tokenDecimals;
                                  }
                              
                                  function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
                                      require(srcQty <= MAX_QTY);
                                      require(rate <= MAX_RATE);
                              
                                      if (dstDecimals >= srcDecimals) {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
                                      } else {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
                                      }
                                  }
                              
                                  function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
                                      require(dstQty <= MAX_QTY);
                                      require(rate <= MAX_RATE);
                              
                                      //source quantity is rounded up. to avoid dest quantity being too low.
                                      uint numerator;
                                      uint denominator;
                                      if (srcDecimals >= dstDecimals) {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
                                          denominator = rate;
                                      } else {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          numerator = (PRECISION * dstQty);
                                          denominator = (rate * (10**(dstDecimals - srcDecimals)));
                                      }
                                      return (numerator + denominator - 1) / denominator; //avoid rounding down errors
                                  }
                              }
                              
                              contract ConversionRates is ConversionRatesInterface, VolumeImbalanceRecorder, Utils {
                              
                                  // bps - basic rate steps. one step is 1 / 10000 of the rate.
                                  struct StepFunction {
                                      int[] x; // quantity for each step. Quantity of each step includes previous steps.
                                      int[] y; // rate change per quantity step  in bps.
                                  }
                              
                                  struct TokenData {
                                      bool listed;  // was added to reserve
                                      bool enabled; // whether trade is enabled
                              
                                      // position in the compact data
                                      uint compactDataArrayIndex;
                                      uint compactDataFieldIndex;
                              
                                      // rate data. base and changes according to quantity and reserve balance.
                                      // generally speaking. Sell rate is 1 / buy rate i.e. the buy in the other direction.
                                      uint baseBuyRate;  // in PRECISION units. see KyberConstants
                                      uint baseSellRate; // PRECISION units. without (sell / buy) spread it is 1 / baseBuyRate
                                      StepFunction buyRateQtyStepFunction; // in bps. higher quantity - bigger the rate.
                                      StepFunction sellRateQtyStepFunction;// in bps. higher the qua
                                      StepFunction buyRateImbalanceStepFunction; // in BPS. higher reserve imbalance - bigger the rate.
                                      StepFunction sellRateImbalanceStepFunction;
                                  }
                              
                                  /*
                                  this is the data for tokenRatesCompactData
                                  but solidity compiler optimizer is sub-optimal, and cannot write this structure in a single storage write
                                  so we represent it as bytes32 and do the byte tricks ourselves.
                                  struct TokenRatesCompactData {
                                      bytes14 buy;  // change buy rate of token from baseBuyRate in 10 bps
                                      bytes14 sell; // change sell rate of token from baseSellRate in 10 bps
                              
                                      uint32 blockNumber;
                                  } */
                                  uint public validRateDurationInBlocks = 10; // rates are valid for this amount of blocks
                                  ERC20[] internal listedTokens;
                                  mapping(address=>TokenData) internal tokenData;
                                  bytes32[] internal tokenRatesCompactData;
                                  uint public numTokensInCurrentCompactData = 0;
                                  address public reserveContract;
                                  uint constant internal NUM_TOKENS_IN_COMPACT_DATA = 14;
                                  uint constant internal BYTES_14_OFFSET = (2 ** (8 * NUM_TOKENS_IN_COMPACT_DATA));
                                  uint constant internal MAX_STEPS_IN_FUNCTION = 10;
                                  int  constant internal MAX_BPS_ADJUSTMENT = 10 ** 11; // 1B %
                                  int  constant internal MIN_BPS_ADJUSTMENT = -100 * 100; // cannot go down by more than 100%
                              
                                  function ConversionRates(address _admin) public VolumeImbalanceRecorder(_admin)
                                      { } // solhint-disable-line no-empty-blocks
                              
                                  function addToken(ERC20 token) public onlyAdmin {
                              
                                      require(!tokenData[token].listed);
                                      tokenData[token].listed = true;
                                      listedTokens.push(token);
                              
                                      if (numTokensInCurrentCompactData == 0) {
                                          tokenRatesCompactData.length++; // add new structure
                                      }
                              
                                      tokenData[token].compactDataArrayIndex = tokenRatesCompactData.length - 1;
                                      tokenData[token].compactDataFieldIndex = numTokensInCurrentCompactData;
                              
                                      numTokensInCurrentCompactData = (numTokensInCurrentCompactData + 1) % NUM_TOKENS_IN_COMPACT_DATA;
                              
                                      setGarbageToVolumeRecorder(token);
                              
                                      setDecimals(token);
                                  }
                              
                                  function setCompactData(bytes14[] buy, bytes14[] sell, uint blockNumber, uint[] indices) public onlyOperator {
                              
                                      require(buy.length == sell.length);
                                      require(indices.length == buy.length);
                                      require(blockNumber <= 0xFFFFFFFF);
                              
                                      uint bytes14Offset = BYTES_14_OFFSET;
                              
                                      for (uint i = 0; i < indices.length; i++) {
                                          require(indices[i] < tokenRatesCompactData.length);
                                          uint data = uint(buy[i]) | uint(sell[i]) * bytes14Offset | (blockNumber * (bytes14Offset * bytes14Offset));
                                          tokenRatesCompactData[indices[i]] = bytes32(data);
                                      }
                                  }
                              
                                  function setBaseRate(
                                      ERC20[] tokens,
                                      uint[] baseBuy,
                                      uint[] baseSell,
                                      bytes14[] buy,
                                      bytes14[] sell,
                                      uint blockNumber,
                                      uint[] indices
                                  )
                                      public
                                      onlyOperator
                                  {
                                      require(tokens.length == baseBuy.length);
                                      require(tokens.length == baseSell.length);
                                      require(sell.length == buy.length);
                                      require(sell.length == indices.length);
                              
                                      for (uint ind = 0; ind < tokens.length; ind++) {
                                          require(tokenData[tokens[ind]].listed);
                                          tokenData[tokens[ind]].baseBuyRate = baseBuy[ind];
                                          tokenData[tokens[ind]].baseSellRate = baseSell[ind];
                                      }
                              
                                      setCompactData(buy, sell, blockNumber, indices);
                                  }
                              
                                  function setQtyStepFunction(
                                      ERC20 token,
                                      int[] xBuy,
                                      int[] yBuy,
                                      int[] xSell,
                                      int[] ySell
                                  )
                                      public
                                      onlyOperator
                                  {
                                      require(xBuy.length == yBuy.length);
                                      require(xSell.length == ySell.length);
                                      require(xBuy.length <= MAX_STEPS_IN_FUNCTION);
                                      require(xSell.length <= MAX_STEPS_IN_FUNCTION);
                                      require(tokenData[token].listed);
                              
                                      tokenData[token].buyRateQtyStepFunction = StepFunction(xBuy, yBuy);
                                      tokenData[token].sellRateQtyStepFunction = StepFunction(xSell, ySell);
                                  }
                              
                                  function setImbalanceStepFunction(
                                      ERC20 token,
                                      int[] xBuy,
                                      int[] yBuy,
                                      int[] xSell,
                                      int[] ySell
                                  )
                                      public
                                      onlyOperator
                                  {
                                      require(xBuy.length == yBuy.length);
                                      require(xSell.length == ySell.length);
                                      require(xBuy.length <= MAX_STEPS_IN_FUNCTION);
                                      require(xSell.length <= MAX_STEPS_IN_FUNCTION);
                                      require(tokenData[token].listed);
                              
                                      tokenData[token].buyRateImbalanceStepFunction = StepFunction(xBuy, yBuy);
                                      tokenData[token].sellRateImbalanceStepFunction = StepFunction(xSell, ySell);
                                  }
                              
                                  function setValidRateDurationInBlocks(uint duration) public onlyAdmin {
                                      validRateDurationInBlocks = duration;
                                  }
                              
                                  function enableTokenTrade(ERC20 token) public onlyAdmin {
                                      require(tokenData[token].listed);
                                      require(tokenControlInfo[token].minimalRecordResolution != 0);
                                      tokenData[token].enabled = true;
                                  }
                              
                                  function disableTokenTrade(ERC20 token) public onlyAlerter {
                                      require(tokenData[token].listed);
                                      tokenData[token].enabled = false;
                                  }
                              
                                  function setReserveAddress(address reserve) public onlyAdmin {
                                      reserveContract = reserve;
                                  }
                              
                                  function recordImbalance(
                                      ERC20 token,
                                      int buyAmount,
                                      uint rateUpdateBlock,
                                      uint currentBlock
                                  )
                                      public
                                  {
                                      require(msg.sender == reserveContract);
                              
                                      if (rateUpdateBlock == 0) rateUpdateBlock = getRateUpdateBlock(token);
                              
                                      return addImbalance(token, buyAmount, rateUpdateBlock, currentBlock);
                                  }
                              
                                  /* solhint-disable function-max-lines */
                                  function getRate(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint) {
                                      // check if trade is enabled
                                      if (!tokenData[token].enabled) return 0;
                                      if (tokenControlInfo[token].minimalRecordResolution == 0) return 0; // token control info not set
                              
                                      // get rate update block
                                      bytes32 compactData = tokenRatesCompactData[tokenData[token].compactDataArrayIndex];
                              
                                      uint updateRateBlock = getLast4Bytes(compactData);
                                      if (currentBlockNumber >= updateRateBlock + validRateDurationInBlocks) return 0; // rate is expired
                                      // check imbalance
                                      int totalImbalance;
                                      int blockImbalance;
                                      (totalImbalance, blockImbalance) = getImbalance(token, updateRateBlock, currentBlockNumber);
                              
                                      // calculate actual rate
                                      int imbalanceQty;
                                      int extraBps;
                                      int8 rateUpdate;
                                      uint rate;
                              
                                      if (buy) {
                                          // start with base rate
                                          rate = tokenData[token].baseBuyRate;
                              
                                          // add rate update
                                          rateUpdate = getRateByteFromCompactData(compactData, token, true);
                                          extraBps = int(rateUpdate) * 10;
                                          rate = addBps(rate, extraBps);
                              
                                          // compute token qty
                                          qty = getTokenQty(token, rate, qty);
                                          imbalanceQty = int(qty);
                                          totalImbalance += imbalanceQty;
                              
                                          // add qty overhead
                                          extraBps = executeStepFunction(tokenData[token].buyRateQtyStepFunction, int(qty));
                                          rate = addBps(rate, extraBps);
                              
                                          // add imbalance overhead
                                          extraBps = executeStepFunction(tokenData[token].buyRateImbalanceStepFunction, totalImbalance);
                                          rate = addBps(rate, extraBps);
                                      } else {
                                          // start with base rate
                                          rate = tokenData[token].baseSellRate;
                              
                                          // add rate update
                                          rateUpdate = getRateByteFromCompactData(compactData, token, false);
                                          extraBps = int(rateUpdate) * 10;
                                          rate = addBps(rate, extraBps);
                              
                                          // compute token qty
                                          imbalanceQty = -1 * int(qty);
                                          totalImbalance += imbalanceQty;
                              
                                          // add qty overhead
                                          extraBps = executeStepFunction(tokenData[token].sellRateQtyStepFunction, int(qty));
                                          rate = addBps(rate, extraBps);
                              
                                          // add imbalance overhead
                                          extraBps = executeStepFunction(tokenData[token].sellRateImbalanceStepFunction, totalImbalance);
                                          rate = addBps(rate, extraBps);
                                      }
                              
                                      if (abs(totalImbalance) >= getMaxTotalImbalance(token)) return 0;
                                      if (abs(blockImbalance + imbalanceQty) >= getMaxPerBlockImbalance(token)) return 0;
                              
                                      return rate;
                                  }
                                  /* solhint-enable function-max-lines */
                              
                                  function getBasicRate(ERC20 token, bool buy) public view returns(uint) {
                                      if (buy)
                                          return tokenData[token].baseBuyRate;
                                      else
                                          return tokenData[token].baseSellRate;
                                  }
                              
                                  function getCompactData(ERC20 token) public view returns(uint, uint, byte, byte) {
                                      require(tokenData[token].listed);
                              
                                      uint arrayIndex = tokenData[token].compactDataArrayIndex;
                                      uint fieldOffset = tokenData[token].compactDataFieldIndex;
                              
                                      return (
                                          arrayIndex,
                                          fieldOffset,
                                          byte(getRateByteFromCompactData(tokenRatesCompactData[arrayIndex], token, true)),
                                          byte(getRateByteFromCompactData(tokenRatesCompactData[arrayIndex], token, false))
                                      );
                                  }
                              
                                  function getTokenBasicData(ERC20 token) public view returns(bool, bool) {
                                      return (tokenData[token].listed, tokenData[token].enabled);
                                  }
                              
                                  /* solhint-disable code-complexity */
                                  function getStepFunctionData(ERC20 token, uint command, uint param) public view returns(int) {
                                      if (command == 0) return int(tokenData[token].buyRateQtyStepFunction.x.length);
                                      if (command == 1) return tokenData[token].buyRateQtyStepFunction.x[param];
                                      if (command == 2) return int(tokenData[token].buyRateQtyStepFunction.y.length);
                                      if (command == 3) return tokenData[token].buyRateQtyStepFunction.y[param];
                              
                                      if (command == 4) return int(tokenData[token].sellRateQtyStepFunction.x.length);
                                      if (command == 5) return tokenData[token].sellRateQtyStepFunction.x[param];
                                      if (command == 6) return int(tokenData[token].sellRateQtyStepFunction.y.length);
                                      if (command == 7) return tokenData[token].sellRateQtyStepFunction.y[param];
                              
                                      if (command == 8) return int(tokenData[token].buyRateImbalanceStepFunction.x.length);
                                      if (command == 9) return tokenData[token].buyRateImbalanceStepFunction.x[param];
                                      if (command == 10) return int(tokenData[token].buyRateImbalanceStepFunction.y.length);
                                      if (command == 11) return tokenData[token].buyRateImbalanceStepFunction.y[param];
                              
                                      if (command == 12) return int(tokenData[token].sellRateImbalanceStepFunction.x.length);
                                      if (command == 13) return tokenData[token].sellRateImbalanceStepFunction.x[param];
                                      if (command == 14) return int(tokenData[token].sellRateImbalanceStepFunction.y.length);
                                      if (command == 15) return tokenData[token].sellRateImbalanceStepFunction.y[param];
                              
                                      revert();
                                  }
                                  /* solhint-enable code-complexity */
                              
                                  function getRateUpdateBlock(ERC20 token) public view returns(uint) {
                                      bytes32 compactData = tokenRatesCompactData[tokenData[token].compactDataArrayIndex];
                                      return getLast4Bytes(compactData);
                                  }
                              
                                  function getListedTokens() public view returns(ERC20[]) {
                                      return listedTokens;
                                  }
                              
                                  function getTokenQty(ERC20 token, uint ethQty, uint rate) internal view returns(uint) {
                                      uint dstDecimals = getDecimals(token);
                                      uint srcDecimals = ETH_DECIMALS;
                              
                                      return calcDstQty(ethQty, srcDecimals, dstDecimals, rate);
                                  }
                              
                                  function getLast4Bytes(bytes32 b) internal pure returns(uint) {
                                      // cannot trust compiler with not turning bit operations into EXP opcode
                                      return uint(b) / (BYTES_14_OFFSET * BYTES_14_OFFSET);
                                  }
                              
                                  function getRateByteFromCompactData(bytes32 data, ERC20 token, bool buy) internal view returns(int8) {
                                      uint fieldOffset = tokenData[token].compactDataFieldIndex;
                                      uint byteOffset;
                                      if (buy)
                                          byteOffset = 32 - NUM_TOKENS_IN_COMPACT_DATA + fieldOffset;
                                      else
                                          byteOffset = 4 + fieldOffset;
                              
                                      return int8(data[byteOffset]);
                                  }
                              
                                  function executeStepFunction(StepFunction f, int x) internal pure returns(int) {
                                      uint len = f.y.length;
                                      for (uint ind = 0; ind < len; ind++) {
                                          if (x <= f.x[ind]) return f.y[ind];
                                      }
                              
                                      return f.y[len-1];
                                  }
                              
                                  function addBps(uint rate, int bps) internal pure returns(uint) {
                                      require(rate <= MAX_RATE);
                                      require(bps >= MIN_BPS_ADJUSTMENT);
                                      require(bps <= MAX_BPS_ADJUSTMENT);
                              
                                      uint maxBps = 100 * 100;
                                      return (rate * uint(int(maxBps) + bps)) / maxBps;
                                  }
                              
                                  function abs(int x) internal pure returns(uint) {
                                      if (x < 0)
                                          return uint(-1 * x);
                                      else
                                          return uint(x);
                                  }
                              }

                              File 18 of 20: SanityRates
                              pragma solidity 0.4.18;
                              
                              interface ERC20 {
                                  function totalSupply() public view returns (uint supply);
                                  function balanceOf(address _owner) public view returns (uint balance);
                                  function transfer(address _to, uint _value) public returns (bool success);
                                  function transferFrom(address _from, address _to, uint _value) public returns (bool success);
                                  function approve(address _spender, uint _value) public returns (bool success);
                                  function allowance(address _owner, address _spender) public view returns (uint remaining);
                                  function decimals() public view returns(uint digits);
                                  event Approval(address indexed _owner, address indexed _spender, uint _value);
                              }
                              
                              contract PermissionGroups {
                              
                                  address public admin;
                                  address public pendingAdmin;
                                  mapping(address=>bool) internal operators;
                                  mapping(address=>bool) internal alerters;
                                  address[] internal operatorsGroup;
                                  address[] internal alertersGroup;
                                  uint constant internal MAX_GROUP_SIZE = 50;
                              
                                  function PermissionGroups() public {
                                      admin = msg.sender;
                                  }
                              
                                  modifier onlyAdmin() {
                                      require(msg.sender == admin);
                                      _;
                                  }
                              
                                  modifier onlyOperator() {
                                      require(operators[msg.sender]);
                                      _;
                                  }
                              
                                  modifier onlyAlerter() {
                                      require(alerters[msg.sender]);
                                      _;
                                  }
                              
                                  function getOperators () external view returns(address[]) {
                                      return operatorsGroup;
                                  }
                              
                                  function getAlerters () external view returns(address[]) {
                                      return alertersGroup;
                                  }
                              
                                  event TransferAdminPending(address pendingAdmin);
                              
                                  /**
                                   * @dev Allows the current admin to set the pendingAdmin address.
                                   * @param newAdmin The address to transfer ownership to.
                                   */
                                  function transferAdmin(address newAdmin) public onlyAdmin {
                                      require(newAdmin != address(0));
                                      TransferAdminPending(pendingAdmin);
                                      pendingAdmin = newAdmin;
                                  }
                              
                                  /**
                                   * @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
                                   * @param newAdmin The address to transfer ownership to.
                                   */
                                  function transferAdminQuickly(address newAdmin) public onlyAdmin {
                                      require(newAdmin != address(0));
                                      TransferAdminPending(newAdmin);
                                      AdminClaimed(newAdmin, admin);
                                      admin = newAdmin;
                                  }
                              
                                  event AdminClaimed( address newAdmin, address previousAdmin);
                              
                                  /**
                                   * @dev Allows the pendingAdmin address to finalize the change admin process.
                                   */
                                  function claimAdmin() public {
                                      require(pendingAdmin == msg.sender);
                                      AdminClaimed(pendingAdmin, admin);
                                      admin = pendingAdmin;
                                      pendingAdmin = address(0);
                                  }
                              
                                  event AlerterAdded (address newAlerter, bool isAdd);
                              
                                  function addAlerter(address newAlerter) public onlyAdmin {
                                      require(!alerters[newAlerter]); // prevent duplicates.
                                      require(alertersGroup.length < MAX_GROUP_SIZE);
                              
                                      AlerterAdded(newAlerter, true);
                                      alerters[newAlerter] = true;
                                      alertersGroup.push(newAlerter);
                                  }
                              
                                  function removeAlerter (address alerter) public onlyAdmin {
                                      require(alerters[alerter]);
                                      alerters[alerter] = false;
                              
                                      for (uint i = 0; i < alertersGroup.length; ++i) {
                                          if (alertersGroup[i] == alerter) {
                                              alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
                                              alertersGroup.length--;
                                              AlerterAdded(alerter, false);
                                              break;
                                          }
                                      }
                                  }
                              
                                  event OperatorAdded(address newOperator, bool isAdd);
                              
                                  function addOperator(address newOperator) public onlyAdmin {
                                      require(!operators[newOperator]); // prevent duplicates.
                                      require(operatorsGroup.length < MAX_GROUP_SIZE);
                              
                                      OperatorAdded(newOperator, true);
                                      operators[newOperator] = true;
                                      operatorsGroup.push(newOperator);
                                  }
                              
                                  function removeOperator (address operator) public onlyAdmin {
                                      require(operators[operator]);
                                      operators[operator] = false;
                              
                                      for (uint i = 0; i < operatorsGroup.length; ++i) {
                                          if (operatorsGroup[i] == operator) {
                                              operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
                                              operatorsGroup.length -= 1;
                                              OperatorAdded(operator, false);
                                              break;
                                          }
                                      }
                                  }
                              }
                              
                              contract Utils {
                              
                                  ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
                                  uint  constant internal PRECISION = (10**18);
                                  uint  constant internal MAX_QTY   = (10**28); // 10B tokens
                                  uint  constant internal MAX_RATE  = (PRECISION * 10**6); // up to 1M tokens per ETH
                                  uint  constant internal MAX_DECIMALS = 18;
                                  uint  constant internal ETH_DECIMALS = 18;
                                  mapping(address=>uint) internal decimals;
                              
                                  function setDecimals(ERC20 token) internal {
                                      if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
                                      else decimals[token] = token.decimals();
                                  }
                              
                                  function getDecimals(ERC20 token) internal view returns(uint) {
                                      if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
                                      uint tokenDecimals = decimals[token];
                                      // technically, there might be token with decimals 0
                                      // moreover, very possible that old tokens have decimals 0
                                      // these tokens will just have higher gas fees.
                                      if(tokenDecimals == 0) return token.decimals();
                              
                                      return tokenDecimals;
                                  }
                              
                                  function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
                                      require(srcQty <= MAX_QTY);
                                      require(rate <= MAX_RATE);
                              
                                      if (dstDecimals >= srcDecimals) {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
                                      } else {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
                                      }
                                  }
                              
                                  function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
                                      require(dstQty <= MAX_QTY);
                                      require(rate <= MAX_RATE);
                              
                                      //source quantity is rounded up. to avoid dest quantity being too low.
                                      uint numerator;
                                      uint denominator;
                                      if (srcDecimals >= dstDecimals) {
                                          require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
                                          numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
                                          denominator = rate;
                                      } else {
                                          require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
                                          numerator = (PRECISION * dstQty);
                                          denominator = (rate * (10**(dstDecimals - srcDecimals)));
                                      }
                                      return (numerator + denominator - 1) / denominator; //avoid rounding down errors
                                  }
                              }
                              
                              contract Withdrawable is PermissionGroups {
                              
                                  event TokenWithdraw(ERC20 token, uint amount, address sendTo);
                              
                                  /**
                                   * @dev Withdraw all ERC20 compatible tokens
                                   * @param token ERC20 The address of the token contract
                                   */
                                  function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
                                      require(token.transfer(sendTo, amount));
                                      TokenWithdraw(token, amount, sendTo);
                                  }
                              
                                  event EtherWithdraw(uint amount, address sendTo);
                              
                                  /**
                                   * @dev Withdraw Ethers
                                   */
                                  function withdrawEther(uint amount, address sendTo) external onlyAdmin {
                                      sendTo.transfer(amount);
                                      EtherWithdraw(amount, sendTo);
                                  }
                              }
                              
                              interface SanityRatesInterface {
                                  function getSanityRate(ERC20 src, ERC20 dest) public view returns(uint);
                              }
                              
                              contract SanityRates is SanityRatesInterface, Withdrawable, Utils {
                                  mapping(address=>uint) public tokenRate;
                                  mapping(address=>uint) public reasonableDiffInBps;
                              
                                  function SanityRates(address _admin) public {
                                      require(_admin != address(0));
                                      admin = _admin;
                                  }
                              
                                  function setReasonableDiff(ERC20[] srcs, uint[] diff) public onlyAdmin {
                                      require(srcs.length == diff.length);
                                      for (uint i = 0; i < srcs.length; i++) {
                                          require(diff[i] <= 100 * 100);
                                          reasonableDiffInBps[srcs[i]] = diff[i];
                                      }
                                  }
                              
                                  function setSanityRates(ERC20[] srcs, uint[] rates) public onlyOperator {
                                      require(srcs.length == rates.length);
                              
                                      for (uint i = 0; i < srcs.length; i++) {
                                          require(rates[i] <= MAX_RATE);
                                          tokenRate[srcs[i]] = rates[i];
                                      }
                                  }
                              
                                  function getSanityRate(ERC20 src, ERC20 dest) public view returns(uint) {
                                      if (src != ETH_TOKEN_ADDRESS && dest != ETH_TOKEN_ADDRESS) return 0;
                              
                                      uint rate;
                                      address token;
                                      if (src == ETH_TOKEN_ADDRESS) {
                                          rate = (PRECISION*PRECISION)/tokenRate[dest];
                                          token = dest;
                                      } else {
                                          rate = tokenRate[src];
                                          token = src;
                                      }
                              
                                      return rate * (10000 + reasonableDiffInBps[token])/10000;
                                  }
                              }

                              File 19 of 20: ContractFeatures
                              pragma solidity ^0.4.21;
                              
                              /*
                                  Contract Features interface
                              */
                              contract IContractFeatures {
                                  function isSupported(address _contract, uint256 _features) public view returns (bool);
                                  function enableFeatures(uint256 _features, bool _enable) public;
                              }
                              
                              /**
                                  Contract Features
                              
                                  Generic contract that allows every contract on the blockchain to define which features it supports.
                                  Other contracts can query this contract to find out whether a given contract on the
                                  blockchain supports a certain feature.
                                  Each contract type can define its own list of feature flags.
                                  Features can be only enabled/disabled by the contract they are defined for.
                              
                                  Features should be defined by each contract type as bit flags, e.g. -
                                  uint256 public constant FEATURE1 = 1 << 0;
                                  uint256 public constant FEATURE2 = 1 << 1;
                                  uint256 public constant FEATURE3 = 1 << 2;
                                  ...
                              */
                              contract ContractFeatures is IContractFeatures {
                                  mapping (address => uint256) private featureFlags;
                              
                                  event FeaturesAddition(address indexed _address, uint256 _features);
                                  event FeaturesRemoval(address indexed _address, uint256 _features);
                              
                                  /**
                                      @dev constructor
                                  */
                                  function ContractFeatures() public {
                                  }
                              
                                  /**
                                      @dev returns true if a given contract supports the given feature(s), false if not
                              
                                      @param _contract    contract address to check support for
                                      @param _features    feature(s) to check for
                              
                                      @return true if the contract supports the feature(s), false if not
                                  */
                                  function isSupported(address _contract, uint256 _features) public view returns (bool) {
                                      return (featureFlags[_contract] & _features) == _features;
                                  }
                              
                                  /**
                                      @dev allows a contract to enable/disable certain feature(s)
                              
                                      @param _features    feature(s) to enable/disable
                                      @param _enable      true to enable the feature(s), false to disabled them
                                  */
                                  function enableFeatures(uint256 _features, bool _enable) public {
                                      if (_enable) {
                                          if (isSupported(msg.sender, _features))
                                              return;
                              
                                          featureFlags[msg.sender] |= _features;
                              
                                          emit FeaturesAddition(msg.sender, _features);
                                      } else {
                                          if (!isSupported(msg.sender, _features))
                                              return;
                              
                                          featureFlags[msg.sender] &= ~_features;
                              
                                          emit FeaturesRemoval(msg.sender, _features);
                                      }
                                  }
                              }

                              File 20 of 20: BancorGasPriceLimit
                              pragma solidity ^0.4.18;
                              
                              
                              contract Utils {
                                  /**
                                      constructor
                                  */
                                  function Utils() public {
                                  }
                              
                                  // 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 != address(0));
                                      _;
                                  }
                              
                                  // 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 pure 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 pure 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 pure returns (uint256) {
                                      uint256 z = _x * _y;
                                      assert(_x == 0 || z / _x == _y);
                                      return z;
                                  }
                              }
                              
                              contract IOwned {
                                  // this function isn't abstract since the compiler emits automatically generated getter functions as external
                                  function owner() public view returns (address) {}
                              
                                  function transferOwnership(address _newOwner) public;
                                  function acceptOwnership() public;
                              }
                              
                              contract Owned is IOwned {
                                  address public owner;
                                  address public newOwner;
                              
                                  event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
                              
                                  /**
                                      @dev constructor
                                  */
                                  function Owned() public {
                                      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 = address(0);
                                  }
                              }
                              
                              
                              
                              contract IBancorGasPriceLimit {
                                  function gasPrice() public view returns (uint256) {}
                                  function validateGasPrice(uint256) public view;
                              }
                              
                              
                              contract BancorGasPriceLimit is IBancorGasPriceLimit, Owned, Utils {
                                  uint256 public gasPrice = 0 wei;    // maximum gas price for bancor transactions
                                  
                                  /**
                                      @dev constructor
                              
                                      @param _gasPrice    gas price limit
                                  */
                                  function BancorGasPriceLimit(uint256 _gasPrice)
                                      public
                                      greaterThanZero(_gasPrice)
                                  {
                                      gasPrice = _gasPrice;
                                  }
                              
                                  /*
                                      @dev gas price getter
                              
                                      @return the current gas price
                                  */
                                  function gasPrice() public view returns (uint256) {
                                      return gasPrice;
                                  }
                              
                                  /*
                                      @dev allows the owner to update the gas price limit
                              
                                      @param _gasPrice    new gas price limit
                                  */
                                  function setGasPrice(uint256 _gasPrice)
                                      public
                                      ownerOnly
                                      greaterThanZero(_gasPrice)
                                  {
                                      gasPrice = _gasPrice;
                                  }
                              
                                  /*
                                      @dev validate that the given gas price is equal to the current network gas price
                              
                                      @param _gasPrice    tested gas price
                                  */
                                  function validateGasPrice(uint256 _gasPrice)
                                      public
                                      view
                                      greaterThanZero(_gasPrice)
                                  {
                                      require(_gasPrice <= gasPrice);
                                  }
                              }