ETH Price: $1,879.55 (+0.54%)

Transaction Decoder

Block:
12961458 at Aug-04-2021 11:00:34 PM +UTC
Transaction Fee:
0.00905067 ETH $17.01
Gas Used:
201,126 Gas / 45 Gwei

Emitted Events:

145 SmartToken.Transfer( _from=StandardPoolConverter, _to=StandardPoolConverter, _value=1702334197608466704170 )
146 StandardPoolConverter.Conversion( _fromToken=0xEeeeeEee...eeeeeEEeE, _toToken=SmartToken, _trader=[Sender] 0xffc041b1c734f8bc0502a9fc0d7c35ab437c416d, _amount=2269386973756688902, _return=1702334197608466704170, _conversionFee=1704038235844311015 )
147 StandardPoolConverter.TokenRateUpdate( _token1=0xEeeeeEee...eeeeeEEeE, _token2=SmartToken, _rateN=63312832392418713830695622, _rateD=84320396887606200958733 )
148 StandardPoolConverter.TokenRateUpdate( _token1=SmartToken, _token2=0xEeeeeEee...eeeeeEEeE, _rateN=84320396887606200958733, _rateD=93051983028496603856411137 )
149 StandardPoolConverter.TokenRateUpdate( _token1=SmartToken, _token2=SmartToken, _rateN=63312832392418713830695622, _rateD=93051983028496603856411137 )
150 BancorNetwork.Conversion( _smartToken=SmartToken, _fromToken=0xEeeeeEee...eeeeeEEeE, _toToken=SmartToken, _fromAmount=2269386973756688902, _toAmount=1702334197608466704170, _trader=[Sender] 0xffc041b1c734f8bc0502a9fc0d7c35ab437c416d )
151 DSToken.Transfer( _from=StandardPoolConverter, _to=[Sender] 0xffc041b1c734f8bc0502a9fc0d7c35ab437c416d, _value=6635517163858334550216 )
152 StandardPoolConverter.Conversion( _fromToken=SmartToken, _toToken=DSToken, _trader=[Sender] 0xffc041b1c734f8bc0502a9fc0d7c35ab437c416d, _amount=1702334197608466704170, _return=6635517163858334550216, _conversionFee=50142447082052905921 )
153 StandardPoolConverter.TokenRateUpdate( _token1=SmartToken, _token2=DSToken, _rateN=2798559336260358855998010, _rateD=714271950388395971003807 )
154 StandardPoolConverter.TokenRateUpdate( _token1=DSToken, _token2=SmartToken, _rateN=714271950388395971003807, _rateD=1108417586571206903829513 )
155 StandardPoolConverter.TokenRateUpdate( _token1=DSToken, _token2=DSToken, _rateN=2798559336260358855998010, _rateD=1108417586571206903829513 )
156 BancorNetwork.Conversion( _smartToken=DSToken, _fromToken=SmartToken, _toToken=DSToken, _fromAmount=1702334197608466704170, _toAmount=6635517163858334550216, _trader=[Sender] 0xffc041b1c734f8bc0502a9fc0d7c35ab437c416d )

Account State Difference:

  Address   Before After State Difference Code
0x1F573D6F...d79a7FF1C
0x48Fb2534...d9d387f94
0x4c9a2bD6...c0f18e5a9
(Bancor: Converter 571)
84,318.127500632444269831 Eth84,320.396887606200958733 Eth2.269386973756688902
0x8d06AFd8...e81C875b8
(Bancor: Converter 568)
(Ethermine)
1,736.73899380576615651 Eth1,736.74804447576615651 Eth0.00905067
0xFfC041B1...B437C416d
2.427138155756688902 Eth
Nonce: 3917
0.148700512 Eth
Nonce: 3918
2.278437643756688902

Execution Trace

ETH 2.269386973756688902 BancorNetwork.convertByPath( _path=[0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0xb1CD6e4153B2a390Cf00A6556b0fC1458C4A5533, 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, 0x3D9E2dA44Af9386484d0D35C29eB62122e4F4742, 0x48Fb253446873234F2fEBbF9BdeAA72d9d387f94], _amount=2269386973756688902, _minReturn=6589094690604574581421, _beneficiary=0x0000000000000000000000000000000000000000, _affiliateAccount=0x0000000000000000000000000000000000000000, _affiliateFee=0 ) => ( 6635517163858334550216 )
  • SmartToken.CALL( )
  • StandardPoolConverter.STATICCALL( )
  • ContractRegistry.addressOf( _contractName=424E54546F6B656E000000000000000000000000000000000000000000000000 ) => ( 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C )
  • SmartToken.CALL( )
  • StandardPoolConverter.STATICCALL( )
  • DSToken.CALL( )
  • StandardPoolConverter.STATICCALL( )
  • ETH 2.269386973756688902 StandardPoolConverter.convert( _sourceToken=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, _targetToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _amount=2269386973756688902, _trader=0xFfC041B1c734f8bC0502A9Fc0d7c35AB437C416d, _beneficiary=0x8d06AFd8E322d39Ebaba6DD98f17a0ae81C875b8 ) => ( 1702334197608466704170 )
    • ContractRegistry.addressOf( _contractName=42616E636F724E6574776F726B00000000000000000000000000000000000000 ) => ( 0x2F9EC37d6CcFFf1caB21733BdaDEdE11c823cCB0 )
    • SmartToken.transfer( _to=0x8d06AFd8E322d39Ebaba6DD98f17a0ae81C875b8, _value=1702334197608466704170 ) => ( success=True )
    • SmartToken.STATICCALL( )
    • StandardPoolConverter.convert( _sourceToken=0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C, _targetToken=0x48Fb253446873234F2fEBbF9BdeAA72d9d387f94, _amount=1702334197608466704170, _trader=0xFfC041B1c734f8bC0502A9Fc0d7c35AB437C416d, _beneficiary=0xFfC041B1c734f8bC0502A9Fc0d7c35AB437C416d ) => ( 6635517163858334550216 )
      • ContractRegistry.addressOf( _contractName=42616E636F724E6574776F726B00000000000000000000000000000000000000 ) => ( 0x2F9EC37d6CcFFf1caB21733BdaDEdE11c823cCB0 )
      • SmartToken.balanceOf( 0x8d06AFd8E322d39Ebaba6DD98f17a0ae81C875b8 ) => ( 714271950388395971003807 )
      • DSToken.transfer( _to=0xFfC041B1c734f8bC0502A9Fc0d7c35AB437C416d, _value=6635517163858334550216 ) => ( True )
      • DSToken.STATICCALL( )
        convertByPath[BancorNetwork (ln:950)]
        File 1 of 8: BancorNetwork
        // 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/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);
        
            // 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);
        }
        
        // File: contracts/IConversionPathFinder.sol
        
        pragma solidity 0.4.26;
        
        
        /*
            Conversion Path Finder interface
        */
        contract IConversionPathFinder {
            function findPath(address _sourceToken, address _targetToken) public view returns (address[] memory);
        }
        
        // 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/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/converter/interfaces/IConverterAnchor.sol
        
        pragma solidity 0.4.26;
        
        
        
        /*
            Converter Anchor interface
        */
        contract IConverterAnchor is IOwned, ITokenHolder {
        }
        
        // 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/IConverter.sol
        
        pragma solidity 0.4.26;
        
        
        
        
        
        /*
            Converter interface
        */
        contract IConverter is IOwned {
            function converterType() public pure returns (uint16);
            function anchor() public view returns (IConverterAnchor) {this;}
            function isActive() public view returns (bool);
        
            function rateAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public view returns (uint256, uint256);
            function convert(IERC20Token _sourceToken,
                             IERC20Token _targetToken,
                             uint256 _amount,
                             address _trader,
                             address _beneficiary) public payable returns (uint256);
        
            function conversionWhitelist() public view returns (IWhitelist) {this;}
            function conversionFee() public view returns (uint32) {this;}
            function maxConversionFee() public view returns (uint32) {this;}
            function reserveBalance(IERC20Token _reserveToken) public view returns (uint256);
            function() external payable;
        
            function transferAnchorOwnership(address _newOwner) public;
            function acceptAnchorOwnership() public;
            function setConversionFee(uint32 _conversionFee) public;
            function setConversionWhitelist(IWhitelist _whitelist) public;
            function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
            function withdrawETH(address _to) public;
            function addReserve(IERC20Token _token, uint32 _ratio) public;
        
            // deprecated, backward compatibility
            function token() public view returns (IConverterAnchor);
            function transferTokenOwnership(address _newOwner) public;
            function acceptTokenOwnership() public;
            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/IBancorFormula.sol
        
        pragma solidity 0.4.26;
        
        /*
            Bancor Formula interface
        */
        contract IBancorFormula {
            function purchaseRate(uint256 _supply,
                                  uint256 _reserveBalance,
                                  uint32 _reserveWeight,
                                  uint256 _amount)
                                  public view returns (uint256);
        
            function saleRate(uint256 _supply,
                              uint256 _reserveBalance,
                              uint32 _reserveWeight,
                              uint256 _amount)
                              public view returns (uint256);
        
            function crossReserveRate(uint256 _sourceReserveBalance,
                                      uint32 _sourceReserveWeight,
                                      uint256 _targetReserveBalance,
                                      uint32 _targetReserveWeight,
                                      uint256 _amount)
                                      public view returns (uint256);
        
            function fundCost(uint256 _supply,
                              uint256 _reserveBalance,
                              uint32 _reserveRatio,
                              uint256 _amount)
                              public view returns (uint256);
        
            function liquidateRate(uint256 _supply,
                                   uint256 _reserveBalance,
                                   uint32 _reserveRatio,
                                   uint256 _amount)
                                   public view returns (uint256);
        }
        
        // 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 {
                _ownerOnly();
                _;
            }
        
            // error message binary size optimization
            function _ownerOnly() internal view {
                require(msg.sender == owner, "ERR_ACCESS_DENIED");
            }
        
            /**
              * @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, "ERR_SAME_OWNER");
                newOwner = _newOwner;
            }
        
            /**
              * @dev used by a new owner to accept an ownership transfer
            */
            function acceptOwnership() public {
                require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
                emit OwnerUpdate(owner, newOwner);
                owner = newOwner;
                newOwner = address(0);
            }
        }
        
        // File: contracts/utility/Utils.sol
        
        pragma solidity 0.4.26;
        
        /**
          * @dev Utilities & Common Modifiers
        */
        contract Utils {
            // verifies that a value is greater than zero
            modifier greaterThanZero(uint256 _value) {
                _greaterThanZero(_value);
                _;
            }
        
            // error message binary size optimization
            function _greaterThanZero(uint256 _value) internal pure {
                require(_value > 0, "ERR_ZERO_VALUE");
            }
        
            // validates an address - currently only checks that it isn't null
            modifier validAddress(address _address) {
                _validAddress(_address);
                _;
            }
        
            // error message binary size optimization
            function _validAddress(address _address) internal pure {
                require(_address != address(0), "ERR_INVALID_ADDRESS");
            }
        
            // verifies that the address is different than this contract address
            modifier notThis(address _address) {
                _notThis(_address);
                _;
            }
        
            // error message binary size optimization
            function _notThis(address _address) internal view {
                require(_address != address(this), "ERR_ADDRESS_IS_SELF");
            }
        }
        
        // 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_REGISTRY = "ContractRegistry";
            bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
            bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
            bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
            bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
            bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
            bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
            bytes32 internal constant 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 onlyOwnerCanUpdateRegistry; // only an owner 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) {
                _only(_contractName);
                _;
            }
        
            // error message binary size optimization
            function _only(bytes32 _contractName) internal view {
                require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED");
            }
        
            /**
              * @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(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
        
                // get the new contract-registry
                IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
        
                // verify that the new contract-registry is different and not zero
                require(newRegistry != address(registry) && newRegistry != address(0), "ERR_INVALID_REGISTRY");
        
                // verify that the new contract-registry is pointing to a non-zero contract-registry
                require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
        
                // save a backup of the current contract-registry before replacing it
                prevRegistry = registry;
        
                // replace the current contract-registry with the new contract-registry
                registry = newRegistry;
            }
        
            /**
              * @dev restores the previous contract-registry
            */
            function restoreRegistry() public ownerOnly {
                // restore the previous contract-registry
                registry = prevRegistry;
            }
        
            /**
              * @dev restricts the permission to update the contract-registry
              *
              * @param _onlyOwnerCanUpdateRegistry  indicates whether or not permission is restricted to owner only
            */
            function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly {
                // change the permission to update the contract-registry
                onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
            }
        
            /**
              * @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/ReentrancyGuard.sol
        
        pragma solidity 0.4.26;
        
        /**
          * @dev ReentrancyGuard
          *
          * The contract provides protection against re-entrancy - calling a function (directly or
          * indirectly) from within itself.
        */
        contract ReentrancyGuard {
            // true while protected code is being executed, false otherwise
            bool private locked = false;
        
            /**
              * @dev ensures instantiation only by sub-contracts
            */
            constructor() internal {}
        
            // protects a function against reentrancy attacks
            modifier protected() {
                _protected();
                locked = true;
                _;
                locked = false;
            }
        
            // error message binary size optimization
            function _protected() internal view {
                require(!locked, "ERR_REENTRANCY");
            }
        }
        
        // File: contracts/utility/TokenHandler.sol
        
        pragma solidity 0.4.26;
        
        
        contract TokenHandler {
            bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)"));
            bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)"));
            bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)"));
        
            /**
              * @dev executes the ERC20 token's `approve` function and reverts upon failure
              * the main purpose of this function is to prevent a non standard ERC20 token
              * from failing silently
              *
              * @param _token   ERC20 token address
              * @param _spender approved address
              * @param _value   allowance amount
            */
            function safeApprove(IERC20Token _token, address _spender, uint256 _value) internal {
               execute(_token, abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value));
            }
        
            /**
              * @dev executes the ERC20 token's `transfer` function and reverts upon failure
              * the main purpose of this function is to prevent a non standard ERC20 token
              * from failing silently
              *
              * @param _token   ERC20 token address
              * @param _to      target address
              * @param _value   transfer amount
            */
            function safeTransfer(IERC20Token _token, address _to, uint256 _value) internal {
               execute(_token, abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value));
            }
        
            /**
              * @dev executes the ERC20 token's `transferFrom` function and reverts upon failure
              * the main purpose of this function is to prevent a non standard ERC20 token
              * from failing silently
              *
              * @param _token   ERC20 token address
              * @param _from    source address
              * @param _to      target address
              * @param _value   transfer amount
            */
            function safeTransferFrom(IERC20Token _token, address _from, address _to, uint256 _value) internal {
               execute(_token, abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value));
            }
        
            /**
              * @dev executes a function on the ERC20 token and reverts upon failure
              * the main purpose of this function is to prevent a non standard ERC20 token
              * from failing silently
              *
              * @param _token   ERC20 token address
              * @param _data    data to pass in to the token's contract for execution
            */
            function execute(IERC20Token _token, bytes memory _data) private {
                uint256[1] memory ret = [uint256(1)];
        
                assembly {
                    let success := call(
                        gas,            // gas remaining
                        _token,         // destination address
                        0,              // no ether
                        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
                        32              // output length
                    )
                    if iszero(success) {
                        revert(0, 0)
                    }
                }
        
                require(ret[0] != 0, "ERR_TRANSFER_FAILED");
            }
        }
        
        // 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, TokenHandler, Owned, Utils {
            /**
              * @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)
            {
                safeTransfer(_token, _to, _amount);
            }
        }
        
        // 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, "ERR_OVERFLOW");
                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, "ERR_UNDERFLOW");
                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, "ERR_OVERFLOW");
                return z;
            }
        
            /**
              * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
              *
              * @param _x   dividend
              * @param _y   divisor
              *
              * @return quotient
            */
            function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
                require(_y > 0, "ERR_DIVIDE_BY_ZERO");
                uint256 c = _x / _y;
                return c;
            }
        }
        
        // File: contracts/token/interfaces/IEtherToken.sol
        
        pragma solidity 0.4.26;
        
        
        /*
            Ether Token interface
        */
        contract IEtherToken is IERC20Token {
            function deposit() public payable;
            function withdraw(uint256 _amount) public;
            function depositTo(address _to) public payable;
            function withdrawTo(address _to, uint256 _amount) public;
        }
        
        // File: contracts/token/interfaces/ISmartToken.sol
        
        pragma solidity 0.4.26;
        
        
        
        
        /*
            Smart Token interface
        */
        contract ISmartToken is IConverterAnchor, 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
        
        pragma solidity 0.4.26;
        
        
        contract IBancorX {
            function token() public view returns (IERC20Token) {this;}
            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
        
        pragma solidity 0.4.26;
        
        
        
        
        
        
        
        
        
        
        
        
        
        // interface of older converters for backward compatibility
        contract ILegacyConverter {
            function change(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
        }
        
        /**
          * @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 - converter anchor & target token.
          * In addition, the first element is always the source token.
          * The converter anchor is only used as a pointer to a converter (since converter addresses are more
          * likely to change as opposed to anchor addresses).
          *
          * Format:
          * [source token, converter anchor, target token, converter anchor, target token...]
        */
        contract BancorNetwork is IBancorNetwork, TokenHolder, ContractRegistryClient, ReentrancyGuard {
            using SafeMath for uint256;
        
            uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000;
            uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000;
            address private constant ETH_RESERVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
        
            struct ConversionStep {
                IConverter converter;
                IConverterAnchor anchor;
                IERC20Token sourceToken;
                IERC20Token targetToken;
                address beneficiary;
                bool isV28OrHigherConverter;
                bool processAffiliateFee;
            }
        
            uint256 public maxAffiliateFee = 30000;     // maximum affiliate-fee
        
            mapping (address => bool) public etherTokens;       // list of all supported ether tokens
        
            /**
              * @dev triggered when a conversion between two tokens occurs
              *
              * @param _smartToken  anchor governed by the converter
              * @param _fromToken   source ERC20 token
              * @param _toToken     target ERC20 token
              * @param _fromAmount  amount converted, in the source token
              * @param _toAmount    amount returned, minus conversion fee
              * @param _trader      wallet that initiated the trade
            */
            event Conversion(
                address indexed _smartToken,
                address indexed _fromToken,
                address indexed _toToken,
                uint256 _fromAmount,
                uint256 _toAmount,
                address _trader
            );
        
            /**
              * @dev initializes a new BancorNetwork instance
              *
              * @param _registry    address of a contract registry contract
            */
            constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public {
                etherTokens[ETH_RESERVE_ADDRESS] = true;
            }
        
            /**
              * @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, "ERR_INVALID_AFFILIATE_FEE");
                maxAffiliateFee = _maxAffiliateFee;
            }
        
            /**
              * @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 returns the conversion path between two tokens in the network
              * note that this method is quite expensive in terms of gas and should generally be called off-chain
              *
              * @param _sourceToken source token address
              * @param _targetToken target token address
              *
              * @return conversion path between the two tokens
            */
            function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[]) {
                IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER));
                return pathFinder.findPath(_sourceToken, _targetToken);
            }
        
            /**
              * @dev returns the expected rate of converting a given amount on a given path
              * note that there is no support for circular paths
              *
              * @param _path        conversion path (see conversion path format above)
              * @param _amount      amount of _path[0] tokens received from the sender
              *
              * @return expected rate
            */
            function rateByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256) {
                uint256 amount;
                uint256 fee;
                uint256 supply;
                uint256 balance;
                uint32 weight;
                IConverter converter;
                IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
        
                amount = _amount;
        
                // verify that the number of elements is larger than 2 and odd
                require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH");
        
                // iterate over the conversion path
                for (uint256 i = 2; i < _path.length; i += 2) {
                    IERC20Token sourceToken = _path[i - 2];
                    IERC20Token anchor = _path[i - 1];
                    IERC20Token targetToken = _path[i];
        
                    converter = IConverter(IConverterAnchor(anchor).owner());
        
                    // backward compatibility
                    sourceToken = getConverterTokenAddress(converter, sourceToken);
                    targetToken = getConverterTokenAddress(converter, targetToken);
        
                    if (targetToken == anchor) { // buy the smart token
                        // check if the current smart token has changed
                        if (i < 3 || anchor != _path[i - 3])
                            supply = ISmartToken(anchor).totalSupply();
        
                        // get the amount & the conversion fee
                        balance = converter.getConnectorBalance(sourceToken);
                        (, weight, , , ) = converter.connectors(sourceToken);
                        amount = formula.purchaseRate(supply, balance, weight, amount);
                        fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION);
                        amount -= fee;
        
                        // update the smart token supply for the next iteration
                        supply = supply.add(amount);
                    }
                    else if (sourceToken == anchor) { // sell the smart token
                        // check if the current smart token has changed
                        if (i < 3 || anchor != _path[i - 3])
                            supply = ISmartToken(anchor).totalSupply();
        
                        // get the amount & the conversion fee
                        balance = converter.getConnectorBalance(targetToken);
                        (, weight, , , ) = converter.connectors(targetToken);
                        amount = formula.saleRate(supply, balance, weight, amount);
                        fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION);
                        amount -= fee;
        
                        // update the smart token supply for the next iteration
                        supply = supply.sub(amount);
                    }
                    else { // cross reserve conversion
                        (amount, fee) = getReturn(converter, sourceToken, targetToken, amount);
                    }
                }
        
                return amount;
            }
        
            /**
              * @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
              * affiliate account/fee can also be passed in to receive a conversion fee (on top of the liquidity provider fees)
              * 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 source token
              * @param _minReturn           if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero
              * @param _beneficiary         account that will receive the conversion result or 0x0 to send the result to the sender account
              * @param _affiliateAccount    wallet address to receive the affiliate fee or 0x0 to disable affiliate fee
              * @param _affiliateFee        affiliate fee in PPM or 0 to disable affiliate fee
              *
              * @return amount of tokens received from the conversion
            */
            function convertByPath(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee)
                public
                payable
                protected
                greaterThanZero(_minReturn)
                returns (uint256)
            {
                // verify that the path contrains at least a single 'hop' and that the number of elements is odd
                require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH");
        
                // validate msg.value and prepare the source token for the conversion
                handleSourceToken(_path[0], IConverterAnchor(_path[1]), _amount);
        
                // check if affiliate fee is enabled
                bool affiliateFeeEnabled = false;
                if (address(_affiliateAccount) == 0) {
                    require(_affiliateFee == 0, "ERR_INVALID_AFFILIATE_FEE");
                }
                else {
                    require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee, "ERR_INVALID_AFFILIATE_FEE");
                    affiliateFeeEnabled = true;
                }
        
                // check if beneficiary is set
                address beneficiary = msg.sender;
                if (_beneficiary != address(0))
                    beneficiary = _beneficiary;
        
                // convert and get the resulting amount
                ConversionStep[] memory data = createConversionData(_path, beneficiary, affiliateFeeEnabled);
                uint256 amount = doConversion(data, _amount, _minReturn, _affiliateAccount, _affiliateFee);
        
                // handle the conversion target tokens
                handleTargetToken(data, amount, beneficiary);
        
                return amount;
            }
        
            /**
              * @dev converts any other token to BNT in the bancor network by following
              a predefined conversion path and transfers the result to an account on a different blockchain
              * 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 source token
              * @param _minReturn           if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero
              * @param _targetBlockchain    blockchain BNT will be issued on
              * @param _targetAccount       address/account on the target blockchain 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 _targetBlockchain,
                bytes32 _targetAccount,
                uint256 _conversionId
            )
                public
                payable
                returns (uint256)
            {
                return xConvert2(_path, _amount, _minReturn, _targetBlockchain, _targetAccount, _conversionId, address(0), 0);
            }
        
            /**
              * @dev converts any other token to BNT in the bancor network by following
              a predefined conversion path and transfers the result to an account on a different blockchain
              * 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 source token
              * @param _minReturn           if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero
              * @param _targetBlockchain    blockchain BNT will be issued on
              * @param _targetAccount       address/account on the target blockchain to send the BNT to
              * @param _conversionId        pre-determined unique (if non zero) id which refers to this transaction
              * @param _affiliateAccount    affiliate account
              * @param _affiliateFee        affiliate fee in PPM
              *
              * @return the amount of BNT received from this conversion
            */
            function xConvert2(
                IERC20Token[] _path,
                uint256 _amount,
                uint256 _minReturn,
                bytes32 _targetBlockchain,
                bytes32 _targetAccount,
                uint256 _conversionId,
                address _affiliateAccount,
                uint256 _affiliateFee
            )
                public
                payable
                greaterThanZero(_minReturn)
                returns (uint256)
            {
                IERC20Token targetToken = _path[_path.length - 1];
                IBancorX bancorX = IBancorX(addressOf(BANCOR_X));
        
                // verify that the destination token is BNT
                require(targetToken == addressOf(BNT_TOKEN), "ERR_INVALID_TARGET_TOKEN");
        
                // convert and get the resulting amount
                uint256 amount = convertByPath(_path, _amount, _minReturn, this, _affiliateAccount, _affiliateFee);
        
                // grant BancorX allowance
                ensureAllowance(targetToken, bancorX, amount);
        
                // transfer the resulting amount to BancorX
                bancorX.xTransfer(_targetBlockchain, _targetAccount, amount, _conversionId);
        
                return amount;
            }
        
            /**
              * @dev allows a user to convert a token that was sent from another blockchain into any other
              * token on the BancorNetwork
              * ideally this transaction is created before the previous conversion is even complete, so
              * so the input amount isn't known at that point - the amount is actually take from the
              * BancorX contract directly by specifying the conversion id
              *
              * @param _path            conversion path
              * @param _bancorX         address of the BancorX contract for the source token
              * @param _conversionId    pre-determined unique (if non zero) id which refers to this conversion
              * @param _minReturn       if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
              * @param _beneficiary     wallet to receive the conversion result
              *
              * @return amount of tokens received from the conversion
            */
            function completeXConversion(IERC20Token[] _path, IBancorX _bancorX, uint256 _conversionId, uint256 _minReturn, address _beneficiary)
                public returns (uint256)
            {
                // verify that the source token is the BancorX token
                require(_path[0] == _bancorX.token(), "ERR_INVALID_SOURCE_TOKEN");
        
                // get conversion amount from BancorX contract
                uint256 amount = _bancorX.getXTransferAmount(_conversionId, msg.sender);
        
                // perform the conversion
                return convertByPath(_path, amount, _minReturn, _beneficiary, address(0), 0);
            }
        
            /**
              * @dev executes the actual conversion by following the conversion path
              *
              * @param _data                conversion data, see ConversionStep struct above
              * @param _amount              amount to convert from, in the source token
              * @param _minReturn           if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero
              * @param _affiliateAccount    affiliate account
              * @param _affiliateFee        affiliate fee in PPM
              *
              * @return amount of tokens received from the conversion
            */
            function doConversion(
                ConversionStep[] _data,
                uint256 _amount,
                uint256 _minReturn,
                address _affiliateAccount,
                uint256 _affiliateFee
            ) private returns (uint256) {
                uint256 toAmount;
                uint256 fromAmount = _amount;
        
                // iterate over the conversion data
                for (uint256 i = 0; i < _data.length; i++) {
                    ConversionStep memory stepData = _data[i];
        
                    // newer converter
                    if (stepData.isV28OrHigherConverter) {
                        // transfer the tokens to the converter only if the network contract currently holds the tokens
                        // not needed with ETH or if it's the first conversion step
                        if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken])
                            safeTransfer(stepData.sourceToken, stepData.converter, fromAmount);
                    }
                    // older converter
                    // if the source token is the smart token, no need to do any transfers as the converter controls it
                    else if (stepData.sourceToken != ISmartToken(stepData.anchor)) {
                        // grant allowance for it to transfer the tokens from the network contract
                        ensureAllowance(stepData.sourceToken, stepData.converter, fromAmount);
                    }
        
                    // do the conversion
                    if (!stepData.isV28OrHigherConverter)
                        toAmount = ILegacyConverter(stepData.converter).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1);
                    else if (etherTokens[stepData.sourceToken])
                        toAmount = stepData.converter.convert.value(msg.value)(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary);
                    else
                        toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary);
        
                    // pay affiliate-fee if needed
                    if (stepData.processAffiliateFee) {
                        uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION);
                        require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED");
                        toAmount -= affiliateAmount;
                    }
        
                    emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender);
                    fromAmount = toAmount;
                }
        
                // ensure the trade meets the minimum requested amount
                require(toAmount >= _minReturn, "ERR_RETURN_TOO_LOW");
        
                return toAmount;
            }
        
            /**
              * @dev validates msg.value and prepares the conversion source token for the conversion
              *
              * @param _sourceToken source token of the first conversion step
              * @param _anchor      converter anchor of the first conversion step
              * @param _amount      amount to convert from, in the source token
            */
            function handleSourceToken(IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount) private {
                IConverter firstConverter = IConverter(_anchor.owner());
                bool isNewerConverter = isV28OrHigherConverter(firstConverter);
        
                // ETH
                if (msg.value > 0) {
                    // validate msg.value
                    require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
        
                    // EtherToken converter - deposit the ETH into the EtherToken
                    // note that it can still be a non ETH converter if the path is wrong
                    // but such conversion will simply revert
                    if (!isNewerConverter)
                        IEtherToken(getConverterEtherTokenAddress(firstConverter)).deposit.value(msg.value)();
                }
                // EtherToken
                else if (etherTokens[_sourceToken]) {
                    // claim the tokens - if the source token is ETH reserve, this call will fail
                    // since in that case the transaction must be sent with msg.value
                    safeTransferFrom(_sourceToken, msg.sender, this, _amount);
        
                    // ETH converter - withdraw the ETH
                    if (isNewerConverter)
                        IEtherToken(_sourceToken).withdraw(_amount);
                }
                // other ERC20 token
                else {
                    // newer converter - transfer the tokens from the sender directly to the converter
                    // otherwise claim the tokens
                    if (isNewerConverter)
                        safeTransferFrom(_sourceToken, msg.sender, firstConverter, _amount);
                    else
                        safeTransferFrom(_sourceToken, msg.sender, this, _amount);
                }
            }
        
            /**
              * @dev handles the conversion target token if the network still holds it at the end of the conversion
              *
              * @param _data        conversion data, see ConversionStep struct above
              * @param _amount      conversion return amount, in the target token
              * @param _beneficiary wallet to receive the conversion result
            */
            function handleTargetToken(ConversionStep[] _data, uint256 _amount, address _beneficiary) private {
                ConversionStep memory stepData = _data[_data.length - 1];
        
                // network contract doesn't hold the tokens, do nothing
                if (stepData.beneficiary != address(this))
                    return;
        
                IERC20Token targetToken = stepData.targetToken;
        
                // ETH / EtherToken
                if (etherTokens[targetToken]) {
                    // newer converter should send ETH directly to the beneficiary
                    assert(!stepData.isV28OrHigherConverter);
        
                    // EtherToken converter - withdraw the ETH and transfer to the beneficiary
                    IEtherToken(targetToken).withdrawTo(_beneficiary, _amount);
                }
                // other ERC20 token
                else {
                    safeTransfer(targetToken, _beneficiary, _amount);
                }
            }
        
            /**
              * @dev creates a memory cache of all conversion steps data to minimize logic and external calls during conversions
              *
              * @param _conversionPath      conversion path, see conversion path format above
              * @param _beneficiary         wallet to receive the conversion result
              * @param _affiliateFeeEnabled true if affiliate fee was requested by the sender, false if not
              *
              * @return cached conversion data to be ingested later on by the conversion flow
            */
            function createConversionData(IERC20Token[] _conversionPath, address _beneficiary, bool _affiliateFeeEnabled) private view returns (ConversionStep[]) {
                ConversionStep[] memory data = new ConversionStep[](_conversionPath.length / 2);
        
                bool affiliateFeeProcessed = false;
                address bntToken = addressOf(BNT_TOKEN);
                // iterate the conversion path and create the conversion data for each step
                uint256 i;
                for (i = 0; i < _conversionPath.length - 1; i += 2) {
                    IConverterAnchor anchor = IConverterAnchor(_conversionPath[i + 1]);
                    IConverter converter = IConverter(anchor.owner());
                    IERC20Token targetToken = _conversionPath[i + 2];
        
                    // check if the affiliate fee should be processed in this step
                    bool processAffiliateFee = _affiliateFeeEnabled && !affiliateFeeProcessed && targetToken == bntToken;
                    if (processAffiliateFee)
                        affiliateFeeProcessed = true;
        
                    data[i / 2] = ConversionStep({
                        // set the converter anchor
                        anchor: anchor,
        
                        // set the converter
                        converter: converter,
        
                        // set the source/target tokens
                        sourceToken: _conversionPath[i],
                        targetToken: targetToken,
        
                        // requires knowledge about the next step, so initialize in the next phase
                        beneficiary: address(0),
        
                        // set flags
                        isV28OrHigherConverter: isV28OrHigherConverter(converter),
                        processAffiliateFee: processAffiliateFee
                    });
                }
        
                // ETH support
                // source is ETH
                ConversionStep memory stepData = data[0];
                if (etherTokens[stepData.sourceToken]) {
                    // newer converter - replace the source token address with ETH reserve address
                    if (stepData.isV28OrHigherConverter)
                        stepData.sourceToken = IERC20Token(ETH_RESERVE_ADDRESS);
                    // older converter - replace the source token with the EtherToken address used by the converter
                    else
                        stepData.sourceToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter));
                }
        
                // target is ETH
                stepData = data[data.length - 1];
                if (etherTokens[stepData.targetToken]) {
                    // newer converter - replace the target token address with ETH reserve address
                    if (stepData.isV28OrHigherConverter)
                        stepData.targetToken = IERC20Token(ETH_RESERVE_ADDRESS);
                    // older converter - replace the target token with the EtherToken address used by the converter
                    else
                        stepData.targetToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter));
                }
        
                // set the beneficiary for each step
                for (i = 0; i < data.length; i++) {
                    stepData = data[i];
        
                    // first check if the converter in this step is newer as older converters don't even support the beneficiary argument
                    if (stepData.isV28OrHigherConverter) {
                        // if affiliate fee is processed in this step, beneficiary is the network contract
                        if (stepData.processAffiliateFee)
                            stepData.beneficiary = this;
                        // if it's the last step, beneficiary is the final beneficiary
                        else if (i == data.length - 1)
                            stepData.beneficiary = _beneficiary;
                        // if the converter in the next step is newer, beneficiary is the next converter
                        else if (data[i + 1].isV28OrHigherConverter)
                            stepData.beneficiary = data[i + 1].converter;
                        // the converter in the next step is older, beneficiary is the network contract
                        else
                            stepData.beneficiary = this;
                    }
                    else {
                        // converter in this step is older, beneficiary is the network contract
                        stepData.beneficiary = this;
                    }
                }
        
                return data;
            }
        
            /**
              * @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 {
                uint256 allowance = _token.allowance(this, _spender);
                if (allowance < _value) {
                    if (allowance > 0)
                        safeApprove(_token, _spender, 0);
                    safeApprove(_token, _spender, _value);
                }
            }
        
            // legacy - returns the address of an EtherToken used by the converter
            function getConverterEtherTokenAddress(IConverter _converter) private view returns (address) {
                uint256 reserveCount = _converter.connectorTokenCount();
                for (uint256 i = 0; i < reserveCount; i++) {
                    address reserveTokenAddress = _converter.connectorTokens(i);
                    if (etherTokens[reserveTokenAddress])
                        return reserveTokenAddress;
                }
        
                return ETH_RESERVE_ADDRESS;
            }
        
            // legacy - if the token is an ether token, returns the ETH reserve address
            // used by the converter, otherwise returns the input token address
            function getConverterTokenAddress(IConverter _converter, IERC20Token _token) private view returns (IERC20Token) {
                if (!etherTokens[_token])
                    return _token;
        
                if (isV28OrHigherConverter(_converter))
                    return IERC20Token(ETH_RESERVE_ADDRESS);
        
                return IERC20Token(getConverterEtherTokenAddress(_converter));
            }
        
            bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)"));
        
            // using assembly code since older converter versions have different return values
            function getReturn(address _dest, address _sourceToken, address _targetToken, uint256 _amount) internal view returns (uint256, uint256) {
                uint256[2] memory ret;
                bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _sourceToken, _targetToken, _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]);
            }
        
            bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()"));
        
            // using assembly code to identify converter version
            // can't rely on the version number since the function had a different signature in older converters
            function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) {
                bool success;
                uint256[1] memory ret;
                bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR);
        
                assembly {
                    success := staticcall(
                        5000,          // isV28OrHigher consumes 190 gas, but just for extra safety
                        _converter,    // 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
                        32             // output length
                    )
                }
        
                return success && ret[0] != 0;
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) {
                return (rateByPath(_path, _amount), 0);
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) {
                return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0);
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function convert2(
                IERC20Token[] _path,
                uint256 _amount,
                uint256 _minReturn,
                address _affiliateAccount,
                uint256 _affiliateFee
            )
                public
                payable
                returns (uint256)
            {
                return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee);
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary) public payable returns (uint256) {
                return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0);
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function convertFor2(
                IERC20Token[] _path,
                uint256 _amount,
                uint256 _minReturn,
                address _beneficiary,
                address _affiliateAccount,
                uint256 _affiliateFee
            )
                public
                payable
                greaterThanZero(_minReturn)
                returns (uint256)
            {
                return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee);
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function claimAndConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public returns (uint256) {
                return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0);
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function claimAndConvert2(
                IERC20Token[] _path,
                uint256 _amount,
                uint256 _minReturn,
                address _affiliateAccount,
                uint256 _affiliateFee
            )
                public
                returns (uint256)
            {
                return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee);
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary) public returns (uint256) {
                return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0);
            }
        
            /**
              * @dev deprecated, backward compatibility
            */
            function claimAndConvertFor2(
                IERC20Token[] _path,
                uint256 _amount,
                uint256 _minReturn,
                address _beneficiary,
                address _affiliateAccount,
                uint256 _affiliateFee
            )
                public
                returns (uint256)
            {
                return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee);
            }
        }

        File 2 of 8: StandardPoolConverter
        // File: @openzeppelin/contracts/math/SafeMath.sol
        
        // SPDX-License-Identifier: MIT
        
        pragma solidity >=0.6.0 <0.8.0;
        
        /**
         * @dev Wrappers over Solidity's arithmetic operations with added overflow
         * checks.
         *
         * Arithmetic operations in Solidity wrap on overflow. This can easily result
         * in bugs, because programmers usually assume that an overflow raises an
         * error, which is the standard behavior in high level programming languages.
         * `SafeMath` restores this intuition by reverting the transaction when an
         * operation overflows.
         *
         * Using this library instead of the unchecked operations eliminates an entire
         * class of bugs, so it's recommended to use it always.
         */
        library SafeMath {
            /**
             * @dev Returns the addition of two unsigned integers, with an overflow flag.
             *
             * _Available since v3.4._
             */
            function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                uint256 c = a + b;
                if (c < a) return (false, 0);
                return (true, c);
            }
        
            /**
             * @dev Returns the substraction of two unsigned integers, with an overflow flag.
             *
             * _Available since v3.4._
             */
            function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                if (b > a) return (false, 0);
                return (true, a - b);
            }
        
            /**
             * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
             *
             * _Available since v3.4._
             */
            function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                // benefit is lost if 'b' is also tested.
                // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                if (a == 0) return (true, 0);
                uint256 c = a * b;
                if (c / a != b) return (false, 0);
                return (true, c);
            }
        
            /**
             * @dev Returns the division of two unsigned integers, with a division by zero flag.
             *
             * _Available since v3.4._
             */
            function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                if (b == 0) return (false, 0);
                return (true, a / b);
            }
        
            /**
             * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
             *
             * _Available since v3.4._
             */
            function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                if (b == 0) return (false, 0);
                return (true, a % b);
            }
        
            /**
             * @dev Returns the addition of two unsigned integers, reverting on
             * overflow.
             *
             * Counterpart to Solidity's `+` operator.
             *
             * Requirements:
             *
             * - Addition cannot overflow.
             */
            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                uint256 c = a + b;
                require(c >= a, "SafeMath: addition overflow");
                return c;
            }
        
            /**
             * @dev Returns the subtraction of two unsigned integers, reverting on
             * overflow (when the result is negative).
             *
             * Counterpart to Solidity's `-` operator.
             *
             * Requirements:
             *
             * - Subtraction cannot overflow.
             */
            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b <= a, "SafeMath: subtraction overflow");
                return a - b;
            }
        
            /**
             * @dev Returns the multiplication of two unsigned integers, reverting on
             * overflow.
             *
             * Counterpart to Solidity's `*` operator.
             *
             * Requirements:
             *
             * - Multiplication cannot overflow.
             */
            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                if (a == 0) return 0;
                uint256 c = a * b;
                require(c / a == b, "SafeMath: multiplication overflow");
                return c;
            }
        
            /**
             * @dev Returns the integer division of two unsigned integers, reverting on
             * division by zero. The result is rounded towards zero.
             *
             * Counterpart to Solidity's `/` operator. Note: this function uses a
             * `revert` opcode (which leaves remaining gas untouched) while Solidity
             * uses an invalid opcode to revert (consuming all remaining gas).
             *
             * Requirements:
             *
             * - The divisor cannot be zero.
             */
            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b > 0, "SafeMath: division by zero");
                return a / b;
            }
        
            /**
             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
             * reverting when dividing by zero.
             *
             * Counterpart to Solidity's `%` operator. This function uses a `revert`
             * opcode (which leaves remaining gas untouched) while Solidity uses an
             * invalid opcode to revert (consuming all remaining gas).
             *
             * Requirements:
             *
             * - The divisor cannot be zero.
             */
            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b > 0, "SafeMath: modulo by zero");
                return a % b;
            }
        
            /**
             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
             * overflow (when the result is negative).
             *
             * CAUTION: This function is deprecated because it requires allocating memory for the error
             * message unnecessarily. For custom revert reasons use {trySub}.
             *
             * Counterpart to Solidity's `-` operator.
             *
             * Requirements:
             *
             * - Subtraction cannot overflow.
             */
            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                require(b <= a, errorMessage);
                return a - b;
            }
        
            /**
             * @dev Returns the integer division of two unsigned integers, reverting with custom message on
             * division by zero. The result is rounded towards zero.
             *
             * CAUTION: This function is deprecated because it requires allocating memory for the error
             * message unnecessarily. For custom revert reasons use {tryDiv}.
             *
             * Counterpart to Solidity's `/` operator. Note: this function uses a
             * `revert` opcode (which leaves remaining gas untouched) while Solidity
             * uses an invalid opcode to revert (consuming all remaining gas).
             *
             * Requirements:
             *
             * - The divisor cannot be zero.
             */
            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                require(b > 0, errorMessage);
                return a / b;
            }
        
            /**
             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
             * reverting with custom message when dividing by zero.
             *
             * CAUTION: This function is deprecated because it requires allocating memory for the error
             * message unnecessarily. For custom revert reasons use {tryMod}.
             *
             * Counterpart to Solidity's `%` operator. This function uses a `revert`
             * opcode (which leaves remaining gas untouched) while Solidity uses an
             * invalid opcode to revert (consuming all remaining gas).
             *
             * Requirements:
             *
             * - The divisor cannot be zero.
             */
            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                require(b > 0, errorMessage);
                return a % b;
            }
        }
        
        // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
        
        
        
        pragma solidity >=0.6.0 <0.8.0;
        
        /**
         * @dev Interface of the ERC20 standard as defined in the EIP.
         */
        interface IERC20 {
            /**
             * @dev Returns the amount of tokens in existence.
             */
            function totalSupply() external view returns (uint256);
        
            /**
             * @dev Returns the amount of tokens owned by `account`.
             */
            function balanceOf(address account) external view returns (uint256);
        
            /**
             * @dev Moves `amount` tokens from the caller's account to `recipient`.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * Emits a {Transfer} event.
             */
            function transfer(address recipient, uint256 amount) external returns (bool);
        
            /**
             * @dev Returns the remaining number of tokens that `spender` will be
             * allowed to spend on behalf of `owner` through {transferFrom}. This is
             * zero by default.
             *
             * This value changes when {approve} or {transferFrom} are called.
             */
            function allowance(address owner, address spender) external view returns (uint256);
        
            /**
             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * IMPORTANT: Beware that changing an allowance with this method brings the risk
             * that someone may use both the old and the new allowance by unfortunate
             * transaction ordering. One possible solution to mitigate this race
             * condition is to first reduce the spender's allowance to 0 and set the
             * desired value afterwards:
             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
             *
             * Emits an {Approval} event.
             */
            function approve(address spender, uint256 amount) external returns (bool);
        
            /**
             * @dev Moves `amount` tokens from `sender` to `recipient` using the
             * allowance mechanism. `amount` is then deducted from the caller's
             * allowance.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * Emits a {Transfer} event.
             */
            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
        
            /**
             * @dev Emitted when `value` tokens are moved from one account (`from`) to
             * another (`to`).
             *
             * Note that `value` may be zero.
             */
            event Transfer(address indexed from, address indexed to, uint256 value);
        
            /**
             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
             * a call to {approve}. `value` is the new allowance.
             */
            event Approval(address indexed owner, address indexed spender, uint256 value);
        }
        
        // File: @openzeppelin/contracts/utils/Address.sol
        
        
        
        pragma solidity >=0.6.2 <0.8.0;
        
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize, which returns 0 for contracts in
                // construction, since the code is only stored at the end of the
                // constructor execution.
        
                uint256 size;
                // solhint-disable-next-line no-inline-assembly
                assembly { size := extcodesize(account) }
                return size > 0;
            }
        
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
        
                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                (bool success, ) = recipient.call{ value: amount }("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
        
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain`call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionCall(target, data, "Address: low-level call failed");
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
        
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                require(isContract(target), "Address: call to non-contract");
        
                // solhint-disable-next-line avoid-low-level-calls
                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                return _verifyCallResult(success, returndata, errorMessage);
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                require(isContract(target), "Address: static call to non-contract");
        
                // solhint-disable-next-line avoid-low-level-calls
                (bool success, bytes memory returndata) = target.staticcall(data);
                return _verifyCallResult(success, returndata, errorMessage);
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                require(isContract(target), "Address: delegate call to non-contract");
        
                // solhint-disable-next-line avoid-low-level-calls
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return _verifyCallResult(success, returndata, errorMessage);
            }
        
            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
        
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
        }
        
        // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
        
        
        
        pragma solidity >=0.6.0 <0.8.0;
        
        
        
        
        /**
         * @title SafeERC20
         * @dev Wrappers around ERC20 operations that throw on failure (when the token
         * contract returns false). Tokens that return no value (and instead revert or
         * throw on failure) are also supported, non-reverting calls are assumed to be
         * successful.
         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
         */
        library SafeERC20 {
            using SafeMath for uint256;
            using Address for address;
        
            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
            }
        
            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
            }
        
            /**
             * @dev Deprecated. This function has issues similar to the ones found in
             * {IERC20-approve}, and its usage is discouraged.
             *
             * Whenever possible, use {safeIncreaseAllowance} and
             * {safeDecreaseAllowance} instead.
             */
            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                // safeApprove should only be called when setting an initial allowance,
                // or when resetting it to zero. To increase and decrease it, use
                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                // solhint-disable-next-line max-line-length
                require((value == 0) || (token.allowance(address(this), spender) == 0),
                    "SafeERC20: approve from non-zero to non-zero allowance"
                );
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
            }
        
            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
            }
        
            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
            }
        
            /**
             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
             * on the return value: the return value is optional (but if data is returned, it must not be false).
             * @param token The token targeted by the call.
             * @param data The call data (encoded using abi.encode or one of its variants).
             */
            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                // the target address contains contract code and also asserts for success in the low-level call.
        
                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                if (returndata.length > 0) { // Return data is optional
                    // solhint-disable-next-line max-line-length
                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                }
            }
        }
        
        // File: solidity/contracts/converter/ConverterVersion.sol
        
        
        pragma solidity 0.6.12;
        
        contract ConverterVersion {
            uint16 public constant version = 46;
        }
        
        // File: solidity/contracts/utility/interfaces/IOwned.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Owned contract interface
        */
        interface IOwned {
            // this function isn't since the compiler emits automatically generated getter functions as external
            function owner() external view returns (address);
        
            function transferOwnership(address _newOwner) external;
        
            function acceptOwnership() external;
        }
        
        // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
        
        
        pragma solidity 0.6.12;
        
        
        /*
            Converter Anchor interface
        */
        interface IConverterAnchor is IOwned {
        
        }
        
        // File: solidity/contracts/converter/interfaces/IConverter.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /*
            Converter interface
        */
        interface IConverter is IOwned {
            function converterType() external pure returns (uint16);
        
            function anchor() external view returns (IConverterAnchor);
        
            function isActive() external view returns (bool);
        
            function targetAmountAndFee(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount
            ) external view returns (uint256, uint256);
        
            function convert(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount,
                address _trader,
                address payable _beneficiary
            ) external payable returns (uint256);
        
            function conversionFee() external view returns (uint32);
        
            function maxConversionFee() external view returns (uint32);
        
            function reserveBalance(IERC20 _reserveToken) external view returns (uint256);
        
            receive() external payable;
        
            function transferAnchorOwnership(address _newOwner) external;
        
            function acceptAnchorOwnership() external;
        
            function setConversionFee(uint32 _conversionFee) external;
        
            function addReserve(IERC20 _token, uint32 _weight) external;
        
            function transferReservesOnUpgrade(address _newConverter) external;
        
            function onUpgradeComplete() external;
        
            // deprecated, backward compatibility
            function token() external view returns (IConverterAnchor);
        
            function transferTokenOwnership(address _newOwner) external;
        
            function acceptTokenOwnership() external;
        
            function connectors(IERC20 _address)
                external
                view
                returns (
                    uint256,
                    uint32,
                    bool,
                    bool,
                    bool
                );
        
            function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256);
        
            function connectorTokens(uint256 _index) external view returns (IERC20);
        
            function connectorTokenCount() external view returns (uint16);
        
            /**
             * @dev triggered when the converter is activated
             *
             * @param _type        converter type
             * @param _anchor      converter anchor
             * @param _activated   true if the converter was activated, false if it was deactivated
             */
            event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
        
            /**
             * @dev triggered when a conversion between two tokens occurs
             *
             * @param _fromToken       source ERC20 token
             * @param _toToken         target ERC20 token
             * @param _trader          wallet that initiated the trade
             * @param _amount          input amount in units of the source token
             * @param _return          output amount minus conversion fee in units of the target token
             * @param _conversionFee   conversion fee in units of the target token
             */
            event Conversion(
                IERC20 indexed _fromToken,
                IERC20 indexed _toToken,
                address indexed _trader,
                uint256 _amount,
                uint256 _return,
                int256 _conversionFee
            );
        
            /**
             * @dev triggered when the rate between two tokens in the converter changes
             * note that the event might be dispatched for rate updates between any two tokens in the converter
             *
             * @param  _token1 address of the first token
             * @param  _token2 address of the second token
             * @param  _rateN  rate of 1 unit of `_token1` in `_token2` (numerator)
             * @param  _rateD  rate of 1 unit of `_token1` in `_token2` (denominator)
             */
            event TokenRateUpdate(IERC20 indexed _token1, IERC20 indexed _token2, uint256 _rateN, uint256 _rateD);
        
            /**
             * @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);
        }
        
        // File: solidity/contracts/converter/interfaces/IConverterUpgrader.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Converter Upgrader interface
        */
        interface IConverterUpgrader {
            function upgrade(bytes32 _version) external;
        
            function upgrade(uint16 _version) external;
        }
        
        // File: solidity/contracts/utility/interfaces/ITokenHolder.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        /*
            Token Holder interface
        */
        interface ITokenHolder is IOwned {
            receive() external payable;
        
            function withdrawTokens(
                IERC20 token,
                address payable to,
                uint256 amount
            ) external;
        
            function withdrawTokensMultiple(
                IERC20[] calldata tokens,
                address payable to,
                uint256[] calldata amounts
            ) external;
        }
        
        // File: solidity/contracts/INetworkSettings.sol
        
        
        pragma solidity 0.6.12;
        
        
        interface INetworkSettings {
            function networkFeeParams() external view returns (ITokenHolder, uint32);
        
            function networkFeeWallet() external view returns (ITokenHolder);
        
            function networkFee() external view returns (uint32);
        }
        
        // File: solidity/contracts/token/interfaces/IDSToken.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /*
            DSToken interface
        */
        interface IDSToken is IConverterAnchor, IERC20 {
            function issue(address _to, uint256 _amount) external;
        
            function destroy(address _from, uint256 _amount) external;
        }
        
        // File: solidity/contracts/utility/MathEx.sol
        
        
        pragma solidity 0.6.12;
        
        /**
         * @dev This library provides a set of complex math operations.
         */
        library MathEx {
            uint256 private constant MAX_EXP_BIT_LEN = 4;
            uint256 private constant MAX_EXP = 2**MAX_EXP_BIT_LEN - 1;
            uint256 private constant MAX_UINT128 = 2**128 - 1;
        
            /**
             * @dev returns the largest integer smaller than or equal to the square root of a positive integer
             *
             * @param _num a positive integer
             *
             * @return the largest integer smaller than or equal to the square root of the positive integer
             */
            function floorSqrt(uint256 _num) internal pure returns (uint256) {
                uint256 x = _num / 2 + 1;
                uint256 y = (x + _num / x) / 2;
                while (x > y) {
                    x = y;
                    y = (x + _num / x) / 2;
                }
                return x;
            }
        
            /**
             * @dev returns the smallest integer larger than or equal to the square root of a positive integer
             *
             * @param _num a positive integer
             *
             * @return the smallest integer larger than or equal to the square root of the positive integer
             */
            function ceilSqrt(uint256 _num) internal pure returns (uint256) {
                uint256 x = floorSqrt(_num);
                return x * x == _num ? x : x + 1;
            }
        
            /**
             * @dev computes a powered ratio
             *
             * @param _n   ratio numerator
             * @param _d   ratio denominator
             * @param _exp ratio exponent
             *
             * @return powered ratio's numerator and denominator
             */
            function poweredRatio(
                uint256 _n,
                uint256 _d,
                uint256 _exp
            ) internal pure returns (uint256, uint256) {
                require(_exp <= MAX_EXP, "ERR_EXP_TOO_LARGE");
        
                uint256[MAX_EXP_BIT_LEN] memory ns;
                uint256[MAX_EXP_BIT_LEN] memory ds;
        
                (ns[0], ds[0]) = reducedRatio(_n, _d, MAX_UINT128);
                for (uint256 i = 0; (_exp >> i) > 1; i++) {
                    (ns[i + 1], ds[i + 1]) = reducedRatio(ns[i] ** 2, ds[i] ** 2, MAX_UINT128);
                }
        
                uint256 n = 1;
                uint256 d = 1;
        
                for (uint256 i = 0; (_exp >> i) > 0; i++) {
                    if (((_exp >> i) & 1) > 0) {
                        (n, d) = reducedRatio(n * ns[i], d * ds[i], MAX_UINT128);
                    }
                }
        
                return (n, d);
            }
        
            /**
             * @dev computes a reduced-scalar ratio
             *
             * @param _n   ratio numerator
             * @param _d   ratio denominator
             * @param _max maximum desired scalar
             *
             * @return ratio's numerator and denominator
             */
            function reducedRatio(
                uint256 _n,
                uint256 _d,
                uint256 _max
            ) internal pure returns (uint256, uint256) {
                (uint256 n, uint256 d) = (_n, _d);
                if (n > _max || d > _max) {
                    (n, d) = normalizedRatio(n, d, _max);
                }
                if (n != d) {
                    return (n, d);
                }
                return (1, 1);
            }
        
            /**
             * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
             */
            function normalizedRatio(
                uint256 _a,
                uint256 _b,
                uint256 _scale
            ) internal pure returns (uint256, uint256) {
                if (_a <= _b) {
                    return accurateRatio(_a, _b, _scale);
                }
                (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
                return (x, y);
            }
        
            /**
             * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b".
             */
            function accurateRatio(
                uint256 _a,
                uint256 _b,
                uint256 _scale
            ) internal pure returns (uint256, uint256) {
                uint256 maxVal = uint256(-1) / _scale;
                if (_a > maxVal) {
                    uint256 c = _a / (maxVal + 1) + 1;
                    _a /= c; // we can now safely compute `_a * _scale`
                    _b /= c;
                }
                if (_a != _b) {
                    uint256 n = _a * _scale;
                    uint256 d = _a + _b; // can overflow
                    if (d >= _a) {
                        // no overflow in `_a + _b`
                        uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x`
                        uint256 y = _scale - x;
                        return (x, y);
                    }
                    if (n < _b - (_b - _a) / 2) {
                        return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b`
                    }
                    return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b`
                }
                return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function
            }
        
            /**
             * @dev computes the nearest integer to a given quotient without overflowing or underflowing.
             */
            function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
                return _n / _d + (_n % _d) / (_d - _d / 2);
            }
        
            /**
             * @dev returns the average number of decimal digits in a given list of positive integers
             *
             * @param _values  list of positive integers
             *
             * @return the average number of decimal digits in the given list of positive integers
             */
            function geometricMean(uint256[] memory _values) internal pure returns (uint256) {
                uint256 numOfDigits = 0;
                uint256 length = _values.length;
                for (uint256 i = 0; i < length; i++) {
                    numOfDigits += decimalLength(_values[i]);
                }
                return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1);
            }
        
            /**
             * @dev returns the number of decimal digits in a given positive integer
             *
             * @param _x   positive integer
             *
             * @return the number of decimal digits in the given positive integer
             */
            function decimalLength(uint256 _x) internal pure returns (uint256) {
                uint256 y = 0;
                for (uint256 x = _x; x > 0; x /= 10) {
                    y++;
                }
                return y;
            }
        
            /**
             * @dev returns the nearest integer to a given quotient
             * the computation is overflow-safe assuming that the input is sufficiently small
             *
             * @param _n   quotient numerator
             * @param _d   quotient denominator
             *
             * @return the nearest integer to the given quotient
             */
            function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) {
                return (_n + _d / 2) / _d;
            }
        
            /**
             * @dev returns the larger of two values
             *
             * @param _val1 the first value
             * @param _val2 the second value
             */
            function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) {
                return _val1 > _val2 ? _val1 : _val2;
            }
        }
        
        // File: solidity/contracts/utility/Owned.sol
        
        
        pragma solidity 0.6.12;
        
        
        /**
         * @dev This contract provides support and utilities for contract ownership.
         */
        contract Owned is IOwned {
            address public override 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 {
                _ownerOnly();
                _;
            }
        
            // error message binary size optimization
            function _ownerOnly() internal view {
                require(msg.sender == owner, "ERR_ACCESS_DENIED");
            }
        
            /**
             * @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 override ownerOnly {
                require(_newOwner != owner, "ERR_SAME_OWNER");
                newOwner = _newOwner;
            }
        
            /**
             * @dev used by a new owner to accept an ownership transfer
             */
            function acceptOwnership() public override {
                require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
                emit OwnerUpdate(owner, newOwner);
                owner = newOwner;
                newOwner = address(0);
            }
        }
        
        // File: solidity/contracts/utility/Utils.sol
        
        
        pragma solidity 0.6.12;
        
        
        /**
         * @dev Utilities & Common Modifiers
         */
        contract Utils {
            uint32 internal constant PPM_RESOLUTION = 1000000;
            IERC20 internal constant NATIVE_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
        
            // verifies that a value is greater than zero
            modifier greaterThanZero(uint256 _value) {
                _greaterThanZero(_value);
                _;
            }
        
            // error message binary size optimization
            function _greaterThanZero(uint256 _value) internal pure {
                require(_value > 0, "ERR_ZERO_VALUE");
            }
        
            // validates an address - currently only checks that it isn't null
            modifier validAddress(address _address) {
                _validAddress(_address);
                _;
            }
        
            // error message binary size optimization
            function _validAddress(address _address) internal pure {
                require(_address != address(0), "ERR_INVALID_ADDRESS");
            }
        
            // ensures that the portion is valid
            modifier validPortion(uint32 _portion) {
                _validPortion(_portion);
                _;
            }
        
            // error message binary size optimization
            function _validPortion(uint32 _portion) internal pure {
                require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
            }
        
            // validates an external address - currently only checks that it isn't null or this
            modifier validExternalAddress(address _address) {
                _validExternalAddress(_address);
                _;
            }
        
            // error message binary size optimization
            function _validExternalAddress(address _address) internal view {
                require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
            }
        
            // ensures that the fee is valid
            modifier validFee(uint32 fee) {
                _validFee(fee);
                _;
            }
        
            // error message binary size optimization
            function _validFee(uint32 fee) internal pure {
                require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE");
            }
        }
        
        // File: solidity/contracts/utility/interfaces/IContractRegistry.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Contract Registry interface
        */
        interface IContractRegistry {
            function addressOf(bytes32 _contractName) external view returns (address);
        }
        
        // File: solidity/contracts/utility/ContractRegistryClient.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /**
         * @dev This is the base contract for ContractRegistry clients.
         */
        contract ContractRegistryClient is Owned, Utils {
            bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
            bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
            bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
            bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
            bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
            bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
            bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
            bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
            bytes32 internal constant BNT_TOKEN = "BNTToken";
            bytes32 internal constant BANCOR_X = "BancorX";
            bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
            bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection";
            bytes32 internal constant NETWORK_SETTINGS = "NetworkSettings";
        
            IContractRegistry public registry; // address of the current contract-registry
            IContractRegistry public prevRegistry; // address of the previous contract-registry
            bool public onlyOwnerCanUpdateRegistry; // only an owner 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) {
                _only(_contractName);
                _;
            }
        
            // error message binary size optimization
            function _only(bytes32 _contractName) internal view {
                require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED");
            }
        
            /**
             * @dev initializes a new ContractRegistryClient instance
             *
             * @param  _registry   address of a contract-registry contract
             */
            constructor(IContractRegistry _registry) internal validAddress(address(_registry)) {
                registry = IContractRegistry(_registry);
                prevRegistry = IContractRegistry(_registry);
            }
        
            /**
             * @dev updates to the new contract-registry
             */
            function updateRegistry() public {
                // verify that this function is permitted
                require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
        
                // get the new contract-registry
                IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
        
                // verify that the new contract-registry is different and not zero
                require(newRegistry != registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY");
        
                // verify that the new contract-registry is pointing to a non-zero contract-registry
                require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
        
                // save a backup of the current contract-registry before replacing it
                prevRegistry = registry;
        
                // replace the current contract-registry with the new contract-registry
                registry = newRegistry;
            }
        
            /**
             * @dev restores the previous contract-registry
             */
            function restoreRegistry() public ownerOnly {
                // restore the previous contract-registry
                registry = prevRegistry;
            }
        
            /**
             * @dev restricts the permission to update the contract-registry
             *
             * @param _onlyOwnerCanUpdateRegistry  indicates whether or not permission is restricted to owner only
             */
            function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly {
                // change the permission to update the contract-registry
                onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
            }
        
            /**
             * @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: solidity/contracts/utility/ReentrancyGuard.sol
        
        
        pragma solidity 0.6.12;
        
        /**
         * @dev This contract provides protection against calling a function
         * (directly or indirectly) from within itself.
         */
        contract ReentrancyGuard {
            uint256 private constant UNLOCKED = 1;
            uint256 private constant LOCKED = 2;
        
            // LOCKED while protected code is being executed, UNLOCKED otherwise
            uint256 private state = UNLOCKED;
        
            /**
             * @dev ensures instantiation only by sub-contracts
             */
            constructor() internal {}
        
            // protects a function against reentrancy attacks
            modifier protected() {
                _protected();
                state = LOCKED;
                _;
                state = UNLOCKED;
            }
        
            // error message binary size optimization
            function _protected() internal view {
                require(state == UNLOCKED, "ERR_REENTRANCY");
            }
        }
        
        // File: solidity/contracts/utility/Time.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Time implementing contract
        */
        contract Time {
            /**
             * @dev returns the current time
             */
            function time() internal view virtual returns (uint256) {
                return block.timestamp;
            }
        }
        
        // File: solidity/contracts/converter/types/standard-pool/StandardPoolConverter.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        
        
        
        
        
        
        
        
        
        /**
         * @dev This contract is a specialized version of the converter, which is
         * optimized for a liquidity pool that has 2 reserves with 50%/50% weights.
         */
        contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time {
            using SafeMath for uint256;
            using SafeERC20 for IERC20;
            using MathEx for *;
        
            uint256 private constant MAX_UINT128 = 2**128 - 1;
            uint256 private constant MAX_UINT112 = 2**112 - 1;
            uint256 private constant MAX_UINT32 = 2**32 - 1;
            uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes;
        
            uint256 private __reserveBalances;
            uint256 private _reserveBalancesProduct;
            IERC20[] private __reserveTokens;
            mapping(IERC20 => uint256) private __reserveIds;
        
            IConverterAnchor public override anchor; // converter anchor contract
            uint32 public override maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000
            uint32 public override conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee
        
            // average rate details:
            // bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1
            // bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1
            // bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1
            // where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1
            uint256 public averageRateInfo;
        
            /**
             * @dev triggered after liquidity is added
             *
             * @param  _provider       liquidity provider
             * @param  _reserveToken   reserve token address
             * @param  _amount         reserve token amount
             * @param  _newBalance     reserve token new balance
             * @param  _newSupply      pool token new supply
             */
            event LiquidityAdded(
                address indexed _provider,
                IERC20 indexed _reserveToken,
                uint256 _amount,
                uint256 _newBalance,
                uint256 _newSupply
            );
        
            /**
             * @dev triggered after liquidity is removed
             *
             * @param  _provider       liquidity provider
             * @param  _reserveToken   reserve token address
             * @param  _amount         reserve token amount
             * @param  _newBalance     reserve token new balance
             * @param  _newSupply      pool token new supply
             */
            event LiquidityRemoved(
                address indexed _provider,
                IERC20 indexed _reserveToken,
                uint256 _amount,
                uint256 _newBalance,
                uint256 _newSupply
            );
        
            /**
             * @dev initializes a new StandardPoolConverter instance
             *
             * @param  _anchor             anchor governed by the converter
             * @param  _registry           address of a contract registry contract
             * @param  _maxConversionFee   maximum conversion fee, represented in ppm
             */
            constructor(
                IConverterAnchor _anchor,
                IContractRegistry _registry,
                uint32 _maxConversionFee
            ) public ContractRegistryClient(_registry) validAddress(address(_anchor)) validConversionFee(_maxConversionFee) {
                anchor = _anchor;
                maxConversionFee = _maxConversionFee;
            }
        
            // ensures that the converter is active
            modifier active() {
                _active();
                _;
            }
        
            // error message binary size optimization
            function _active() internal view {
                require(isActive(), "ERR_INACTIVE");
            }
        
            // ensures that the converter is not active
            modifier inactive() {
                _inactive();
                _;
            }
        
            // error message binary size optimization
            function _inactive() internal view {
                require(!isActive(), "ERR_ACTIVE");
            }
        
            // validates a reserve token address - verifies that the address belongs to one of the reserve tokens
            modifier validReserve(IERC20 _address) {
                _validReserve(_address);
                _;
            }
        
            // error message binary size optimization
            function _validReserve(IERC20 _address) internal view {
                require(__reserveIds[_address] != 0, "ERR_INVALID_RESERVE");
            }
        
            // validates conversion fee
            modifier validConversionFee(uint32 _conversionFee) {
                _validConversionFee(_conversionFee);
                _;
            }
        
            // error message binary size optimization
            function _validConversionFee(uint32 _conversionFee) internal pure {
                require(_conversionFee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE");
            }
        
            // validates reserve weight
            modifier validReserveWeight(uint32 _weight) {
                _validReserveWeight(_weight);
                _;
            }
        
            // error message binary size optimization
            function _validReserveWeight(uint32 _weight) internal pure {
                require(_weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT");
            }
        
            /**
             * @dev returns the converter type
             *
             * @return see the converter types in the the main contract doc
             */
            function converterType() public pure virtual override returns (uint16) {
                return 3;
            }
        
            /**
             * @dev deposits ether
             * can only be called if the converter has an ETH reserve
             */
            receive() external payable override(IConverter) validReserve(NATIVE_TOKEN_ADDRESS) {}
        
            /**
             * @dev checks whether or not the converter version is 28 or higher
             *
             * @return true, since the converter version is 28 or higher
             */
            function isV28OrHigher() public pure returns (bool) {
                return true;
            }
        
            /**
             * @dev returns true if the converter is active, false otherwise
             *
             * @return true if the converter is active, false otherwise
             */
            function isActive() public view virtual override returns (bool) {
                return anchor.owner() == address(this);
            }
        
            /**
             * @dev transfers the anchor ownership
             * the new owner needs to accept the transfer
             * can only be called by the converter upgrader while the upgrader is the owner
             * note that prior to version 28, you should use 'transferAnchorOwnership' instead
             *
             * @param _newOwner    new token owner
             */
            function transferAnchorOwnership(address _newOwner) public override ownerOnly only(CONVERTER_UPGRADER) {
                anchor.transferOwnership(_newOwner);
            }
        
            /**
             * @dev accepts ownership of the anchor after an ownership transfer
             * most converters are also activated as soon as they accept the anchor ownership
             * can only be called by the contract owner
             * note that prior to version 28, you should use 'acceptTokenOwnership' instead
             */
            function acceptAnchorOwnership() public virtual override ownerOnly {
                // verify the the converter has exactly two reserves
                require(reserveTokenCount() == 2, "ERR_INVALID_RESERVE_COUNT");
                anchor.acceptOwnership();
                syncReserveBalances(0);
                emit Activation(converterType(), anchor, true);
            }
        
            /**
             * @dev updates the current conversion fee
             * can only be called by the contract owner
             *
             * @param _conversionFee new conversion fee, represented in ppm
             */
            function setConversionFee(uint32 _conversionFee) public override ownerOnly {
                require(_conversionFee <= maxConversionFee, "ERR_INVALID_CONVERSION_FEE");
                emit ConversionFeeUpdate(conversionFee, _conversionFee);
                conversionFee = _conversionFee;
            }
        
            /**
             * @dev transfers reserve balances to a new converter during an upgrade
             * can only be called by the converter upgraded which should be set at its owner
             *
             * @param _newConverter address of the converter to receive the new amount
             */
            function transferReservesOnUpgrade(address _newConverter)
                external
                override
                protected
                ownerOnly
                only(CONVERTER_UPGRADER)
            {
                uint256 reserveCount = __reserveTokens.length;
                for (uint256 i = 0; i < reserveCount; ++i) {
                    IERC20 reserveToken = __reserveTokens[i];
        
                    uint256 amount;
                    if (reserveToken == NATIVE_TOKEN_ADDRESS) {
                        amount = address(this).balance;
                    } else {
                        amount = reserveToken.balanceOf(address(this));
                    }
        
                    safeTransfer(reserveToken, _newConverter, amount);
        
                    syncReserveBalance(reserveToken);
                }
            }
        
            /**
             * @dev upgrades the converter to the latest version
             * can only be called by the owner
             * note that the owner needs to call acceptOwnership on the new converter after the upgrade
             */
            function upgrade() public ownerOnly {
                IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER));
        
                // trigger de-activation event
                emit Activation(converterType(), anchor, false);
        
                transferOwnership(address(converterUpgrader));
                converterUpgrader.upgrade(version);
                acceptOwnership();
            }
        
            /**
             * @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic
             */
            function onUpgradeComplete()
                external
                override
                protected
                ownerOnly
                only(CONVERTER_UPGRADER)
            {
                (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
                _reserveBalancesProduct = reserveBalance0 * reserveBalance1;
            }
        
            /**
             * @dev returns the number of reserve tokens
             * 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 returns the array of reserve tokens
             *
             * @return array of reserve tokens
             */
            function reserveTokens() public view returns (IERC20[] memory) {
                return __reserveTokens;
            }
        
            /**
             * @dev defines a new reserve token for the converter
             * can only be called by the owner while the converter is inactive
             *
             * @param _token   address of the reserve token
             * @param _weight  reserve weight, represented in ppm, 1-1000000
             */
            function addReserve(IERC20 _token, uint32 _weight)
                public
                virtual
                override
                ownerOnly
                inactive
                validExternalAddress(address(_token))
                validReserveWeight(_weight)
            {
                // validate input
                require(address(_token) != address(anchor) && __reserveIds[_token] == 0, "ERR_INVALID_RESERVE");
                require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT");
        
                __reserveTokens.push(_token);
                __reserveIds[_token] = __reserveTokens.length;
            }
        
            /**
             * @dev returns the reserve's weight
             * added in version 28
             *
             * @param _reserveToken    reserve token contract address
             *
             * @return reserve weight
             */
            function reserveWeight(IERC20 _reserveToken) public view validReserve(_reserveToken) returns (uint32) {
                return PPM_RESOLUTION / 2;
            }
        
            /**
             * @dev returns the balance of a given reserve token
             *
             * @param _reserveToken    reserve token contract address
             *
             * @return the balance of the given reserve token
             */
            function reserveBalance(IERC20 _reserveToken) public view override returns (uint256) {
                uint256 reserveId = __reserveIds[_reserveToken];
                require(reserveId != 0, "ERR_INVALID_RESERVE");
                return reserveBalance(reserveId);
            }
        
            /**
             * @dev returns the balances of both reserve tokens
             *
             * @return the balances of both reserve tokens
             */
            function reserveBalances() public view returns (uint256, uint256) {
                return reserveBalances(1, 2);
            }
        
            /**
             * @dev syncs all stored reserve balances
             */
            function syncReserveBalances() external {
                syncReserveBalances(0);
            }
        
            /**
             * @dev calculates the accumulated network fee and transfers it to the network fee wallet
             */
            function processNetworkFees() external protected {
                (uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0);
                _reserveBalancesProduct = reserveBalance0 * reserveBalance1;
            }
        
            /**
             * @dev calculates the accumulated network fee and transfers it to the network fee wallet
             *
             * @param _value amount of ether to exclude from the ether reserve balance (if relevant)
             *
             * @return new reserve balances
             */
            function processNetworkFees(uint256 _value) internal returns (uint256, uint256) {
                syncReserveBalances(_value);
                (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
                (ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
                reserveBalance0 -= fee0;
                reserveBalance1 -= fee1;
                setReserveBalances(1, 2, reserveBalance0, reserveBalance1);
                safeTransfer(__reserveTokens[0], address(wallet), fee0);
                safeTransfer(__reserveTokens[1], address(wallet), fee1);
                return (reserveBalance0, reserveBalance1);
            }
        
            /**
             * @dev returns the reserve balances of the given reserve tokens minus their corresponding fees
             *
             * @param _reserveTokens reserve tokens
             *
             * @return reserve balances minus their corresponding fees
             */
            function baseReserveBalances(IERC20[] memory _reserveTokens) internal view returns (uint256[2] memory) {
                uint256 reserveId0 = __reserveIds[_reserveTokens[0]];
                uint256 reserveId1 = __reserveIds[_reserveTokens[1]];
                (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1);
                (, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
                return [reserveBalance0 - fee0, reserveBalance1 - fee1];
            }
        
            /**
             * @dev converts a specific amount of source tokens to target tokens
             * can only be called by the bancor network contract
             *
             * @param _sourceToken source ERC20 token
             * @param _targetToken target ERC20 token
             * @param _amount      amount of tokens to convert (in units of the source token)
             * @param _trader      address of the caller who executed the conversion
             * @param _beneficiary wallet to receive the conversion result
             *
             * @return amount of tokens received (in units of the target token)
             */
            function convert(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount,
                address _trader,
                address payable _beneficiary
            ) public payable override protected only(BANCOR_NETWORK) returns (uint256) {
                // validate input
                require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
        
                return doConvert(_sourceToken, _targetToken, _amount, _trader, _beneficiary);
            }
        
            /**
             * @dev returns the conversion fee for a given target amount
             *
             * @param _targetAmount  target amount
             *
             * @return conversion fee
             */
            function calculateFee(uint256 _targetAmount) internal view returns (uint256) {
                return _targetAmount.mul(conversionFee) / PPM_RESOLUTION;
            }
        
            /**
             * @dev returns the conversion fee taken from a given target amount
             *
             * @param _targetAmount  target amount
             *
             * @return conversion fee
             */
            function calculateFeeInv(uint256 _targetAmount) internal view returns (uint256) {
                return _targetAmount.mul(conversionFee).div(PPM_RESOLUTION - conversionFee);
            }
        
            /**
             * @dev loads the stored reserve balance for a given reserve id
             *
             * @param _reserveId   reserve id
             */
            function reserveBalance(uint256 _reserveId) internal view returns (uint256) {
                return decodeReserveBalance(__reserveBalances, _reserveId);
            }
        
            /**
             * @dev loads the stored reserve balances
             *
             * @param _sourceId    source reserve id
             * @param _targetId    target reserve id
             */
            function reserveBalances(uint256 _sourceId, uint256 _targetId) internal view returns (uint256, uint256) {
                require((_sourceId == 1 && _targetId == 2) || (_sourceId == 2 && _targetId == 1), "ERR_INVALID_RESERVES");
                return decodeReserveBalances(__reserveBalances, _sourceId, _targetId);
            }
        
            /**
             * @dev stores the stored reserve balance for a given reserve id
             *
             * @param _reserveId       reserve id
             * @param _reserveBalance  reserve balance
             */
            function setReserveBalance(uint256 _reserveId, uint256 _reserveBalance) internal {
                require(_reserveBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
                uint256 otherBalance = decodeReserveBalance(__reserveBalances, 3 - _reserveId);
                __reserveBalances = encodeReserveBalances(_reserveBalance, _reserveId, otherBalance, 3 - _reserveId);
            }
        
            /**
             * @dev stores the stored reserve balances
             *
             * @param _sourceId        source reserve id
             * @param _targetId        target reserve id
             * @param _sourceBalance   source reserve balance
             * @param _targetBalance   target reserve balance
             */
            function setReserveBalances(
                uint256 _sourceId,
                uint256 _targetId,
                uint256 _sourceBalance,
                uint256 _targetBalance
            ) internal {
                require(_sourceBalance <= MAX_UINT128 && _targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
                __reserveBalances = encodeReserveBalances(_sourceBalance, _sourceId, _targetBalance, _targetId);
            }
        
            /**
             * @dev syncs the stored reserve balance for a given reserve with the real reserve balance
             *
             * @param _reserveToken    address of the reserve token
             */
            function syncReserveBalance(IERC20 _reserveToken) internal {
                uint256 reserveId = __reserveIds[_reserveToken];
                uint256 balance =
                    _reserveToken == NATIVE_TOKEN_ADDRESS ? address(this).balance : _reserveToken.balanceOf(address(this));
                setReserveBalance(reserveId, balance);
            }
        
            /**
             * @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant)
             *
             * @param _value   amount of ether to exclude from the ether reserve balance (if relevant)
             */
            function syncReserveBalances(uint256 _value) internal {
                IERC20 _reserveToken0 = __reserveTokens[0];
                IERC20 _reserveToken1 = __reserveTokens[1];
                uint256 balance0 =
                    _reserveToken0 == NATIVE_TOKEN_ADDRESS
                        ? address(this).balance - _value
                        : _reserveToken0.balanceOf(address(this));
                uint256 balance1 =
                    _reserveToken1 == NATIVE_TOKEN_ADDRESS
                        ? address(this).balance - _value
                        : _reserveToken1.balanceOf(address(this));
                setReserveBalances(1, 2, balance0, balance1);
            }
        
            /**
             * @dev helper, dispatches the Conversion event
             *
             * @param _sourceToken     source ERC20 token
             * @param _targetToken     target ERC20 token
             * @param _trader          address of the caller who executed the conversion
             * @param _amount          amount purchased/sold (in the source token)
             * @param _returnAmount    amount returned (in the target token)
             */
            function dispatchConversionEvent(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                address _trader,
                uint256 _amount,
                uint256 _returnAmount,
                uint256 _feeAmount
            ) internal {
                emit Conversion(_sourceToken, _targetToken, _trader, _amount, _returnAmount, int256(_feeAmount));
            }
        
            /**
             * @dev returns the expected amount and expected fee for converting one reserve to another
             *
             * @param _sourceToken address of the source reserve token contract
             * @param _targetToken address of the target reserve token contract
             * @param _amount      amount of source reserve tokens converted
             *
             * @return expected amount in units of the target reserve token
             * @return expected fee in units of the target reserve token
             */
            function targetAmountAndFee(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount
            ) public view virtual override active returns (uint256, uint256) {
                uint256 sourceId = __reserveIds[_sourceToken];
                uint256 targetId = __reserveIds[_targetToken];
        
                (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
        
                return targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
            }
        
            /**
             * @dev returns the expected amount and expected fee for converting one reserve to another
             *
             * @param _sourceBalance    balance in the source reserve token contract
             * @param _targetBalance    balance in the target reserve token contract
             * @param _amount           amount of source reserve tokens converted
             *
             * @return expected amount in units of the target reserve token
             * @return expected fee in units of the target reserve token
             */
            function targetAmountAndFee(
                IERC20, /* _sourceToken */
                IERC20, /* _targetToken */
                uint256 _sourceBalance,
                uint256 _targetBalance,
                uint256 _amount
            ) internal view virtual returns (uint256, uint256) {
                uint256 amount = crossReserveTargetAmount(_sourceBalance, _targetBalance, _amount);
        
                uint256 fee = calculateFee(amount);
        
                return (amount - fee, fee);
            }
        
            /**
             * @dev returns the required amount and expected fee for converting one reserve to another
             *
             * @param _sourceToken address of the source reserve token contract
             * @param _targetToken address of the target reserve token contract
             * @param _amount      amount of target reserve tokens desired
             *
             * @return required amount in units of the source reserve token
             * @return expected fee in units of the target reserve token
             */
            function sourceAmountAndFee(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount
            ) public view virtual active returns (uint256, uint256) {
                uint256 sourceId = __reserveIds[_sourceToken];
                uint256 targetId = __reserveIds[_targetToken];
        
                (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
        
                uint256 fee = calculateFeeInv(_amount);
        
                uint256 amount = crossReserveSourceAmount(sourceBalance, targetBalance, _amount.add(fee));
        
                return (amount, fee);
            }
        
            /**
             * @dev converts a specific amount of source tokens to target tokens
             *
             * @param _sourceToken source ERC20 token
             * @param _targetToken target ERC20 token
             * @param _amount      amount of tokens to convert (in units of the source token)
             * @param _trader      address of the caller who executed the conversion
             * @param _beneficiary wallet to receive the conversion result
             *
             * @return amount of tokens received (in units of the target token)
             */
            function doConvert(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount,
                address _trader,
                address payable _beneficiary
            ) internal returns (uint256) {
                // update the recent average rate
                updateRecentAverageRate();
        
                uint256 sourceId = __reserveIds[_sourceToken];
                uint256 targetId = __reserveIds[_targetToken];
        
                (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
        
                // get the target amount minus the conversion fee and the conversion fee
                (uint256 amount, uint256 fee) =
                    targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
        
                // ensure that the trade gives something in return
                require(amount != 0, "ERR_ZERO_TARGET_AMOUNT");
        
                // ensure that the trade won't deplete the reserve balance
                assert(amount < targetBalance);
        
                // ensure that the input amount was already deposited
                uint256 actualSourceBalance;
                if (_sourceToken == NATIVE_TOKEN_ADDRESS) {
                    actualSourceBalance = address(this).balance;
                    require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
                } else {
                    actualSourceBalance = _sourceToken.balanceOf(address(this));
                    require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= _amount, "ERR_INVALID_AMOUNT");
                }
        
                // sync the reserve balances
                setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - amount);
        
                // transfer funds to the beneficiary in the to reserve token
                safeTransfer(_targetToken, _beneficiary, amount);
        
                // dispatch the conversion event
                dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
        
                // dispatch rate updates
                dispatchTokenRateUpdateEvents(_sourceToken, _targetToken, actualSourceBalance, targetBalance - amount);
        
                return amount;
            }
        
            /**
             * @dev returns the recent average rate of 1 `_token` in the other reserve token units
             *
             * @param _token   token to get the rate for
             *
             * @return recent average rate between the reserves (numerator)
             * @return recent average rate between the reserves (denominator)
             */
            function recentAverageRate(IERC20 _token) external view validReserve(_token) returns (uint256, uint256) {
                // get the recent average rate of reserve 0
                uint256 rate = calcRecentAverageRate(averageRateInfo);
        
                uint256 rateN = decodeAverageRateN(rate);
                uint256 rateD = decodeAverageRateD(rate);
        
                if (_token == __reserveTokens[0]) {
                    return (rateN, rateD);
                }
        
                return (rateD, rateN);
            }
        
            /**
             * @dev updates the recent average rate if needed
             */
            function updateRecentAverageRate() internal {
                uint256 averageRateInfo1 = averageRateInfo;
                uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1);
                if (averageRateInfo1 != averageRateInfo2) {
                    averageRateInfo = averageRateInfo2;
                }
            }
        
            /**
             * @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units
             *
             * @param _averageRateInfo a local copy of the `averageRateInfo` state-variable
             *
             * @return recent average rate between the reserves
             */
            function calcRecentAverageRate(uint256 _averageRateInfo) internal view returns (uint256) {
                // get the previous average rate and its update-time
                uint256 prevAverageRateT = decodeAverageRateT(_averageRateInfo);
                uint256 prevAverageRateN = decodeAverageRateN(_averageRateInfo);
                uint256 prevAverageRateD = decodeAverageRateD(_averageRateInfo);
        
                // get the elapsed time since the previous average rate was calculated
                uint256 currentTime = time();
                uint256 timeElapsed = currentTime - prevAverageRateT;
        
                // if the previous average rate was calculated in the current block, the average rate remains unchanged
                if (timeElapsed == 0) {
                    return _averageRateInfo;
                }
        
                // get the current rate between the reserves
                (uint256 currentRateD, uint256 currentRateN) = reserveBalances();
        
                // if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate
                if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) {
                    (currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112);
                    return encodeAverageRateInfo(currentTime, currentRateN, currentRateD);
                }
        
                uint256 x = prevAverageRateD.mul(currentRateN);
                uint256 y = prevAverageRateN.mul(currentRateD);
        
                // since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath:
                uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed));
                uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD);
        
                (newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112);
                return encodeAverageRateInfo(currentTime, newRateN, newRateD);
            }
        
            /**
             * @dev increases the pool's liquidity and mints new shares in the pool to the caller
             *
             * @param _reserveTokens   address of each reserve token
             * @param _reserveAmounts  amount of each reserve token
             * @param _minReturn       token minimum return-amount
             *
             * @return amount of pool tokens issued
             */
            function addLiquidity(
                IERC20[] memory _reserveTokens,
                uint256[] memory _reserveAmounts,
                uint256 _minReturn
            ) public payable protected active returns (uint256) {
                // verify the user input
                verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn);
        
                // if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH
                for (uint256 i = 0; i < 2; i++) {
                    if (_reserveTokens[i] == NATIVE_TOKEN_ADDRESS) {
                        require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH");
                    }
                }
        
                // if the input value of ETH is larger than zero, then verify that one of the reserves is ETH
                if (msg.value > 0) {
                    require(__reserveIds[NATIVE_TOKEN_ADDRESS] != 0, "ERR_NO_ETH_RESERVE");
                }
        
                // save a local copy of the pool token
                IDSToken poolToken = IDSToken(address(anchor));
        
                // get the total supply
                uint256 totalSupply = poolToken.totalSupply();
        
                uint256[2] memory prevReserveBalances;
                uint256[2] memory newReserveBalances;
        
                // process the network fees and get the reserve balances
                (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value);
        
                uint256 amount;
                uint256[2] memory reserveAmounts;
        
                // calculate the amount of pool tokens to mint for the caller
                // and the amount of reserve tokens to transfer from the caller
                if (totalSupply == 0) {
                    amount = MathEx.geometricMean(_reserveAmounts);
                    reserveAmounts[0] = _reserveAmounts[0];
                    reserveAmounts[1] = _reserveAmounts[1];
                } else {
                    (amount, reserveAmounts) = addLiquidityAmounts(
                        _reserveTokens,
                        _reserveAmounts,
                        prevReserveBalances,
                        totalSupply
                    );
                }
        
                uint256 newPoolTokenSupply = totalSupply.add(amount);
                for (uint256 i = 0; i < 2; i++) {
                    IERC20 reserveToken = _reserveTokens[i];
                    uint256 reserveAmount = reserveAmounts[i];
                    require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT");
                    assert(reserveAmount <= _reserveAmounts[i]);
        
                    // transfer each one of the reserve amounts from the user to the pool
                    if (reserveToken != NATIVE_TOKEN_ADDRESS) {
                        // ETH has already been transferred as part of the transaction
                        reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount);
                    } else if (_reserveAmounts[i] > reserveAmount) {
                        // transfer the extra amount of ETH back to the user
                        msg.sender.transfer(_reserveAmounts[i] - reserveAmount);
                    }
        
                    // save the new reserve balance
                    newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount);
        
                    emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
        
                    // dispatch the `TokenRateUpdate` event for the pool token
                    emit TokenRateUpdate(poolToken, reserveToken, newReserveBalances[i], newPoolTokenSupply);
                }
        
                // set the reserve balances
                setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
        
                // set the reserve balances product
                _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
        
                // verify that the equivalent amount of tokens is equal to or larger than the user's expectation
                require(amount >= _minReturn, "ERR_RETURN_TOO_LOW");
        
                // issue the tokens to the user
                poolToken.issue(msg.sender, amount);
        
                // return the amount of pool tokens issued
                return amount;
            }
        
            /**
             * @dev get the amount of pool tokens to mint for the caller
             * and the amount of reserve tokens to transfer from the caller
             *
             * @param _reserveAmounts   amount of each reserve token
             * @param _reserveBalances  balance of each reserve token
             * @param _totalSupply      total supply of pool tokens
             *
             * @return amount of pool tokens to mint for the caller
             * @return amount of reserve tokens to transfer from the caller
             */
            function addLiquidityAmounts(
                IERC20[] memory, /* _reserveTokens */
                uint256[] memory _reserveAmounts,
                uint256[2] memory _reserveBalances,
                uint256 _totalSupply
            ) internal view virtual returns (uint256, uint256[2] memory) {
                this;
        
                uint256 index =
                    _reserveAmounts[0].mul(_reserveBalances[1]) < _reserveAmounts[1].mul(_reserveBalances[0]) ? 0 : 1;
                uint256 amount = fundSupplyAmount(_totalSupply, _reserveBalances[index], _reserveAmounts[index]);
        
                uint256[2] memory reserveAmounts =
                    [fundCost(_totalSupply, _reserveBalances[0], amount), fundCost(_totalSupply, _reserveBalances[1], amount)];
        
                return (amount, reserveAmounts);
            }
        
            /**
             * @dev decreases the pool's liquidity and burns the caller's shares in the pool
             *
             * @param _amount                  token amount
             * @param _reserveTokens           address of each reserve token
             * @param _reserveMinReturnAmounts minimum return-amount of each reserve token
             *
             * @return the amount of each reserve token granted for the given amount of pool tokens
             */
            function removeLiquidity(
                uint256 _amount,
                IERC20[] memory _reserveTokens,
                uint256[] memory _reserveMinReturnAmounts
            ) public protected active returns (uint256[] memory) {
                // verify the user input
                bool inputRearranged = verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);
        
                // save a local copy of the pool token
                IDSToken poolToken = IDSToken(address(anchor));
        
                // get the total supply BEFORE destroying the user tokens
                uint256 totalSupply = poolToken.totalSupply();
        
                // destroy the user tokens
                poolToken.destroy(msg.sender, _amount);
        
                uint256 newPoolTokenSupply = totalSupply.sub(_amount);
        
                uint256[2] memory prevReserveBalances;
                uint256[2] memory newReserveBalances;
        
                // process the network fees and get the reserve balances
                (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0);
        
                uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, totalSupply, prevReserveBalances);
        
                for (uint256 i = 0; i < 2; i++) {
                    IERC20 reserveToken = _reserveTokens[i];
                    uint256 reserveAmount = reserveAmounts[i];
                    require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
        
                    // save the new reserve balance
                    newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount);
        
                    // transfer each one of the reserve amounts from the pool to the user
                    safeTransfer(reserveToken, msg.sender, reserveAmount);
        
                    emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
        
                    // dispatch the `TokenRateUpdate` event for the pool token
                    emit TokenRateUpdate(poolToken, reserveToken, newReserveBalances[i], newPoolTokenSupply);
                }
        
                // set the reserve balances
                setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
        
                // set the reserve balances product
                _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
        
                if (inputRearranged) {
                    uint256 tempReserveAmount = reserveAmounts[0];
                    reserveAmounts[0] = reserveAmounts[1];
                    reserveAmounts[1] = tempReserveAmount;
                }
        
                // return the amount of each reserve token granted for the given amount of pool tokens
                return reserveAmounts;
            }
        
            /**
             * @dev given the amount of one of the reserve tokens to add liquidity of,
             * returns the required amount of each one of the other reserve tokens
             * since an empty pool can be funded with any list of non-zero input amounts,
             * this function assumes that the pool is not empty (has already been funded)
             *
             * @param _reserveTokens       address of each reserve token
             * @param _reserveTokenIndex   index of the relevant reserve token
             * @param _reserveAmount       amount of the relevant reserve token
             *
             * @return the required amount of each one of the reserve tokens
             */
            function addLiquidityCost(
                IERC20[] memory _reserveTokens,
                uint256 _reserveTokenIndex,
                uint256 _reserveAmount
            ) public view returns (uint256[] memory) {
                uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
                uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
                uint256 amount = fundSupplyAmount(totalSupply, baseBalances[_reserveTokenIndex], _reserveAmount);
        
                uint256[] memory reserveAmounts = new uint256[](2);
                reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], amount);
                reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], amount);
                return reserveAmounts;
            }
        
            /**
             * @dev returns the amount of pool tokens entitled for given amounts of reserve tokens
             * since an empty pool can be funded with any list of non-zero input amounts,
             * this function assumes that the pool is not empty (has already been funded)
             *
             * @param _reserveTokens   address of each reserve token
             * @param _reserveAmounts  amount of each reserve token
             *
             * @return the amount of pool tokens entitled for the given amounts of reserve tokens
             */
            function addLiquidityReturn(IERC20[] memory _reserveTokens, uint256[] memory _reserveAmounts)
                public
                view
                returns (uint256)
            {
                uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
                uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
                (uint256 amount, ) = addLiquidityAmounts(_reserveTokens, _reserveAmounts, baseBalances, totalSupply);
                return amount;
            }
        
            /**
             * @dev returns the amount of each reserve token entitled for a given amount of pool tokens
             *
             * @param _amount          amount of pool tokens
             * @param _reserveTokens   address of each reserve token
             *
             * @return the amount of each reserve token entitled for the given amount of pool tokens
             */
            function removeLiquidityReturn(uint256 _amount, IERC20[] memory _reserveTokens)
                public
                view
                returns (uint256[] memory)
            {
                uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
                uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
                return removeLiquidityReserveAmounts(_amount, totalSupply, baseBalances);
            }
        
            /**
             * @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
             * we take this input in order to allow specifying the corresponding reserve amounts in any order
             * this function rearranges the input arrays according to the converter's array of reserve tokens
             *
             * @param _reserveTokens   array of reserve tokens
             * @param _reserveAmounts  array of reserve amounts
             * @param _amount          token amount
             *
             * @return true if the function has rearranged the input arrays; false otherwise
             */
            function verifyLiquidityInput(
                IERC20[] memory _reserveTokens,
                uint256[] memory _reserveAmounts,
                uint256 _amount
            ) private view returns (bool) {
                require(validReserveAmounts(_reserveAmounts) && _amount > 0, "ERR_ZERO_AMOUNT");
        
                uint256 reserve0Id = __reserveIds[_reserveTokens[0]];
                uint256 reserve1Id = __reserveIds[_reserveTokens[1]];
        
                if (reserve0Id == 2 && reserve1Id == 1) {
                    IERC20 tempReserveToken = _reserveTokens[0];
                    _reserveTokens[0] = _reserveTokens[1];
                    _reserveTokens[1] = tempReserveToken;
                    uint256 tempReserveAmount = _reserveAmounts[0];
                    _reserveAmounts[0] = _reserveAmounts[1];
                    _reserveAmounts[1] = tempReserveAmount;
                    return true;
                }
        
                require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE");
                return false;
            }
        
            /**
             * @dev checks whether or not both reserve amounts are larger than zero
             *
             * @param _reserveAmounts  array of reserve amounts
             *
             * @return true if both reserve amounts are larger than zero; false otherwise
             */
            function validReserveAmounts(uint256[] memory _reserveAmounts) internal pure virtual returns (bool) {
                return _reserveAmounts[0] > 0 && _reserveAmounts[1] > 0;
            }
        
            /**
             * @dev returns the amount of each reserve token entitled for a given amount of pool tokens
             *
             * @param _amount          amount of pool tokens
             * @param _totalSupply     total supply of pool tokens
             * @param _reserveBalances balance of each reserve token
             *
             * @return the amount of each reserve token entitled for the given amount of pool tokens
             */
            function removeLiquidityReserveAmounts(
                uint256 _amount,
                uint256 _totalSupply,
                uint256[2] memory _reserveBalances
            ) private pure returns (uint256[] memory) {
                uint256[] memory reserveAmounts = new uint256[](2);
                reserveAmounts[0] = liquidateReserveAmount(_totalSupply, _reserveBalances[0], _amount);
                reserveAmounts[1] = liquidateReserveAmount(_totalSupply, _reserveBalances[1], _amount);
                return reserveAmounts;
            }
        
            /**
             * @dev dispatches token rate update events for the reserve tokens and the pool token
             *
             * @param _sourceToken     address of the source reserve token
             * @param _targetToken     address of the target reserve token
             * @param _sourceBalance   balance of the source reserve token
             * @param _targetBalance   balance of the target reserve token
             */
            function dispatchTokenRateUpdateEvents(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _sourceBalance,
                uint256 _targetBalance
            ) private {
                // save a local copy of the pool token
                IDSToken poolToken = IDSToken(address(anchor));
        
                // get the total supply of pool tokens
                uint256 poolTokenSupply = poolToken.totalSupply();
        
                // dispatch token rate update event for the reserve tokens
                emit TokenRateUpdate(_sourceToken, _targetToken, _targetBalance, _sourceBalance);
        
                // dispatch token rate update events for the pool token
                emit TokenRateUpdate(poolToken, _sourceToken, _sourceBalance, poolTokenSupply);
                emit TokenRateUpdate(poolToken, _targetToken, _targetBalance, poolTokenSupply);
            }
        
            function encodeReserveBalance(uint256 _balance, uint256 _id) private pure returns (uint256) {
                assert(_balance <= MAX_UINT128 && (_id == 1 || _id == 2));
                return _balance << ((_id - 1) * 128);
            }
        
            function decodeReserveBalance(uint256 _balances, uint256 _id) private pure returns (uint256) {
                assert(_id == 1 || _id == 2);
                return (_balances >> ((_id - 1) * 128)) & MAX_UINT128;
            }
        
            function encodeReserveBalances(
                uint256 _balance0,
                uint256 _id0,
                uint256 _balance1,
                uint256 _id1
            ) private pure returns (uint256) {
                return encodeReserveBalance(_balance0, _id0) | encodeReserveBalance(_balance1, _id1);
            }
        
            function decodeReserveBalances(
                uint256 _balances,
                uint256 _id0,
                uint256 _id1
            ) private pure returns (uint256, uint256) {
                return (decodeReserveBalance(_balances, _id0), decodeReserveBalance(_balances, _id1));
            }
        
            function encodeAverageRateInfo(
                uint256 _averageRateT,
                uint256 _averageRateN,
                uint256 _averageRateD
            ) private pure returns (uint256) {
                assert(_averageRateT <= MAX_UINT32 && _averageRateN <= MAX_UINT112 && _averageRateD <= MAX_UINT112);
                return (_averageRateT << 224) | (_averageRateN << 112) | _averageRateD;
            }
        
            function decodeAverageRateT(uint256 _averageRateInfo) private pure returns (uint256) {
                return _averageRateInfo >> 224;
            }
        
            function decodeAverageRateN(uint256 _averageRateInfo) private pure returns (uint256) {
                return (_averageRateInfo >> 112) & MAX_UINT112;
            }
        
            function decodeAverageRateD(uint256 _averageRateInfo) private pure returns (uint256) {
                return _averageRateInfo & MAX_UINT112;
            }
        
            /**
             * @dev returns the largest integer smaller than or equal to the square root of a given value
             *
             * @param x the given value
             *
             * @return the largest integer smaller than or equal to the square root of the given value
             */
            function floorSqrt(uint256 x) private pure returns (uint256) {
                return x > 0 ? MathEx.floorSqrt(x) : 0;
            }
        
            function crossReserveTargetAmount(
                uint256 _sourceReserveBalance,
                uint256 _targetReserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
        
                return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount);
            }
        
            function crossReserveSourceAmount(
                uint256 _sourceReserveBalance,
                uint256 _targetReserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
                require(_amount < _targetReserveBalance, "ERR_INVALID_AMOUNT");
        
                if (_amount == 0) {
                    return 0;
                }
        
                return (_sourceReserveBalance.mul(_amount) - 1) / (_targetReserveBalance - _amount) + 1;
            }
        
            function fundCost(
                uint256 _supply,
                uint256 _reserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_supply > 0, "ERR_INVALID_SUPPLY");
                require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
        
                // special case for 0 amount
                if (_amount == 0) {
                    return 0;
                }
        
                return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
            }
        
            function fundSupplyAmount(
                uint256 _supply,
                uint256 _reserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_supply > 0, "ERR_INVALID_SUPPLY");
                require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
        
                // special case for 0 amount
                if (_amount == 0) {
                    return 0;
                }
        
                return _amount.mul(_supply) / _reserveBalance;
            }
        
            function liquidateReserveAmount(
                uint256 _supply,
                uint256 _reserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_supply > 0, "ERR_INVALID_SUPPLY");
                require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
                require(_amount <= _supply, "ERR_INVALID_AMOUNT");
        
                // special case for 0 amount
                if (_amount == 0) {
                    return 0;
                }
        
                // special case for liquidating the entire supply
                if (_amount == _supply) {
                    return _reserveBalance;
                }
        
                return _amount.mul(_reserveBalance) / _supply;
            }
        
            /**
             * @dev returns the network wallet and fees
             *
             * @param reserveBalance0 1st reserve balance
             * @param reserveBalance1 2nd reserve balance
             *
             * @return the network wallet
             * @return the network fee on the 1st reserve
             * @return the network fee on the 2nd reserve
             */
            function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1)
                private
                view
                returns (
                    ITokenHolder,
                    uint256,
                    uint256
                )
            {
                uint256 prevPoint = floorSqrt(_reserveBalancesProduct);
                uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1);
        
                if (prevPoint >= currPoint) {
                    return (ITokenHolder(address(0)), 0, 0);
                }
        
                (ITokenHolder networkFeeWallet, uint32 networkFee) =
                    INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams();
                uint256 n = (currPoint - prevPoint) * networkFee;
                uint256 d = currPoint * PPM_RESOLUTION;
                return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d));
            }
        
            /**
             * @dev transfers funds held by the contract and sends them to an account
             *
             * @param token ERC20 token contract address
             * @param to account to receive the new amount
             * @param amount amount to withdraw
             */
            function safeTransfer(
                IERC20 token,
                address to,
                uint256 amount
            ) private {
                if (amount == 0) {
                    return;
                }
        
                if (token == NATIVE_TOKEN_ADDRESS) {
                    payable(to).transfer(amount);
                } else {
                    token.safeTransfer(to, amount);
                }
            }
        
            /**
             * @dev deprecated since version 28, backward compatibility - use only for earlier versions
             */
            function token() public view override returns (IConverterAnchor) {
                return anchor;
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function transferTokenOwnership(address _newOwner) public override ownerOnly {
                transferAnchorOwnership(_newOwner);
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function acceptTokenOwnership() public override ownerOnly {
                acceptAnchorOwnership();
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function connectors(IERC20 _address)
                public
                view
                override
                returns (
                    uint256,
                    uint32,
                    bool,
                    bool,
                    bool
                )
            {
                uint256 reserveId = __reserveIds[_address];
                if (reserveId != 0) {
                    return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true);
                }
                return (0, 0, false, false, false);
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function connectorTokens(uint256 _index) public view override returns (IERC20) {
                return __reserveTokens[_index];
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function connectorTokenCount() public view override returns (uint16) {
                return reserveTokenCount();
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function getConnectorBalance(IERC20 _connectorToken) public view override returns (uint256) {
                return reserveBalance(_connectorToken);
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function getReturn(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount
            ) public view returns (uint256, uint256) {
                return targetAmountAndFee(_sourceToken, _targetToken, _amount);
            }
        }
        

        File 3 of 8: StandardPoolConverter
        // File: @openzeppelin/contracts/math/SafeMath.sol
        
        // SPDX-License-Identifier: MIT
        
        pragma solidity >=0.6.0 <0.8.0;
        
        /**
         * @dev Wrappers over Solidity's arithmetic operations with added overflow
         * checks.
         *
         * Arithmetic operations in Solidity wrap on overflow. This can easily result
         * in bugs, because programmers usually assume that an overflow raises an
         * error, which is the standard behavior in high level programming languages.
         * `SafeMath` restores this intuition by reverting the transaction when an
         * operation overflows.
         *
         * Using this library instead of the unchecked operations eliminates an entire
         * class of bugs, so it's recommended to use it always.
         */
        library SafeMath {
            /**
             * @dev Returns the addition of two unsigned integers, with an overflow flag.
             *
             * _Available since v3.4._
             */
            function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                uint256 c = a + b;
                if (c < a) return (false, 0);
                return (true, c);
            }
        
            /**
             * @dev Returns the substraction of two unsigned integers, with an overflow flag.
             *
             * _Available since v3.4._
             */
            function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                if (b > a) return (false, 0);
                return (true, a - b);
            }
        
            /**
             * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
             *
             * _Available since v3.4._
             */
            function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                // benefit is lost if 'b' is also tested.
                // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                if (a == 0) return (true, 0);
                uint256 c = a * b;
                if (c / a != b) return (false, 0);
                return (true, c);
            }
        
            /**
             * @dev Returns the division of two unsigned integers, with a division by zero flag.
             *
             * _Available since v3.4._
             */
            function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                if (b == 0) return (false, 0);
                return (true, a / b);
            }
        
            /**
             * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
             *
             * _Available since v3.4._
             */
            function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                if (b == 0) return (false, 0);
                return (true, a % b);
            }
        
            /**
             * @dev Returns the addition of two unsigned integers, reverting on
             * overflow.
             *
             * Counterpart to Solidity's `+` operator.
             *
             * Requirements:
             *
             * - Addition cannot overflow.
             */
            function add(uint256 a, uint256 b) internal pure returns (uint256) {
                uint256 c = a + b;
                require(c >= a, "SafeMath: addition overflow");
                return c;
            }
        
            /**
             * @dev Returns the subtraction of two unsigned integers, reverting on
             * overflow (when the result is negative).
             *
             * Counterpart to Solidity's `-` operator.
             *
             * Requirements:
             *
             * - Subtraction cannot overflow.
             */
            function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b <= a, "SafeMath: subtraction overflow");
                return a - b;
            }
        
            /**
             * @dev Returns the multiplication of two unsigned integers, reverting on
             * overflow.
             *
             * Counterpart to Solidity's `*` operator.
             *
             * Requirements:
             *
             * - Multiplication cannot overflow.
             */
            function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                if (a == 0) return 0;
                uint256 c = a * b;
                require(c / a == b, "SafeMath: multiplication overflow");
                return c;
            }
        
            /**
             * @dev Returns the integer division of two unsigned integers, reverting on
             * division by zero. The result is rounded towards zero.
             *
             * Counterpart to Solidity's `/` operator. Note: this function uses a
             * `revert` opcode (which leaves remaining gas untouched) while Solidity
             * uses an invalid opcode to revert (consuming all remaining gas).
             *
             * Requirements:
             *
             * - The divisor cannot be zero.
             */
            function div(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b > 0, "SafeMath: division by zero");
                return a / b;
            }
        
            /**
             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
             * reverting when dividing by zero.
             *
             * Counterpart to Solidity's `%` operator. This function uses a `revert`
             * opcode (which leaves remaining gas untouched) while Solidity uses an
             * invalid opcode to revert (consuming all remaining gas).
             *
             * Requirements:
             *
             * - The divisor cannot be zero.
             */
            function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                require(b > 0, "SafeMath: modulo by zero");
                return a % b;
            }
        
            /**
             * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
             * overflow (when the result is negative).
             *
             * CAUTION: This function is deprecated because it requires allocating memory for the error
             * message unnecessarily. For custom revert reasons use {trySub}.
             *
             * Counterpart to Solidity's `-` operator.
             *
             * Requirements:
             *
             * - Subtraction cannot overflow.
             */
            function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                require(b <= a, errorMessage);
                return a - b;
            }
        
            /**
             * @dev Returns the integer division of two unsigned integers, reverting with custom message on
             * division by zero. The result is rounded towards zero.
             *
             * CAUTION: This function is deprecated because it requires allocating memory for the error
             * message unnecessarily. For custom revert reasons use {tryDiv}.
             *
             * Counterpart to Solidity's `/` operator. Note: this function uses a
             * `revert` opcode (which leaves remaining gas untouched) while Solidity
             * uses an invalid opcode to revert (consuming all remaining gas).
             *
             * Requirements:
             *
             * - The divisor cannot be zero.
             */
            function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                require(b > 0, errorMessage);
                return a / b;
            }
        
            /**
             * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
             * reverting with custom message when dividing by zero.
             *
             * CAUTION: This function is deprecated because it requires allocating memory for the error
             * message unnecessarily. For custom revert reasons use {tryMod}.
             *
             * Counterpart to Solidity's `%` operator. This function uses a `revert`
             * opcode (which leaves remaining gas untouched) while Solidity uses an
             * invalid opcode to revert (consuming all remaining gas).
             *
             * Requirements:
             *
             * - The divisor cannot be zero.
             */
            function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                require(b > 0, errorMessage);
                return a % b;
            }
        }
        
        // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
        
        
        
        pragma solidity >=0.6.0 <0.8.0;
        
        /**
         * @dev Interface of the ERC20 standard as defined in the EIP.
         */
        interface IERC20 {
            /**
             * @dev Returns the amount of tokens in existence.
             */
            function totalSupply() external view returns (uint256);
        
            /**
             * @dev Returns the amount of tokens owned by `account`.
             */
            function balanceOf(address account) external view returns (uint256);
        
            /**
             * @dev Moves `amount` tokens from the caller's account to `recipient`.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * Emits a {Transfer} event.
             */
            function transfer(address recipient, uint256 amount) external returns (bool);
        
            /**
             * @dev Returns the remaining number of tokens that `spender` will be
             * allowed to spend on behalf of `owner` through {transferFrom}. This is
             * zero by default.
             *
             * This value changes when {approve} or {transferFrom} are called.
             */
            function allowance(address owner, address spender) external view returns (uint256);
        
            /**
             * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * IMPORTANT: Beware that changing an allowance with this method brings the risk
             * that someone may use both the old and the new allowance by unfortunate
             * transaction ordering. One possible solution to mitigate this race
             * condition is to first reduce the spender's allowance to 0 and set the
             * desired value afterwards:
             * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
             *
             * Emits an {Approval} event.
             */
            function approve(address spender, uint256 amount) external returns (bool);
        
            /**
             * @dev Moves `amount` tokens from `sender` to `recipient` using the
             * allowance mechanism. `amount` is then deducted from the caller's
             * allowance.
             *
             * Returns a boolean value indicating whether the operation succeeded.
             *
             * Emits a {Transfer} event.
             */
            function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
        
            /**
             * @dev Emitted when `value` tokens are moved from one account (`from`) to
             * another (`to`).
             *
             * Note that `value` may be zero.
             */
            event Transfer(address indexed from, address indexed to, uint256 value);
        
            /**
             * @dev Emitted when the allowance of a `spender` for an `owner` is set by
             * a call to {approve}. `value` is the new allowance.
             */
            event Approval(address indexed owner, address indexed spender, uint256 value);
        }
        
        // File: @openzeppelin/contracts/utils/Address.sol
        
        
        
        pragma solidity >=0.6.2 <0.8.0;
        
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize, which returns 0 for contracts in
                // construction, since the code is only stored at the end of the
                // constructor execution.
        
                uint256 size;
                // solhint-disable-next-line no-inline-assembly
                assembly { size := extcodesize(account) }
                return size > 0;
            }
        
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
        
                // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                (bool success, ) = recipient.call{ value: amount }("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
        
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain`call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionCall(target, data, "Address: low-level call failed");
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
        
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                require(isContract(target), "Address: call to non-contract");
        
                // solhint-disable-next-line avoid-low-level-calls
                (bool success, bytes memory returndata) = target.call{ value: value }(data);
                return _verifyCallResult(success, returndata, errorMessage);
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                require(isContract(target), "Address: static call to non-contract");
        
                // solhint-disable-next-line avoid-low-level-calls
                (bool success, bytes memory returndata) = target.staticcall(data);
                return _verifyCallResult(success, returndata, errorMessage);
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
        
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                require(isContract(target), "Address: delegate call to non-contract");
        
                // solhint-disable-next-line avoid-low-level-calls
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return _verifyCallResult(success, returndata, errorMessage);
            }
        
            function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
        
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
        }
        
        // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
        
        
        
        pragma solidity >=0.6.0 <0.8.0;
        
        
        
        
        /**
         * @title SafeERC20
         * @dev Wrappers around ERC20 operations that throw on failure (when the token
         * contract returns false). Tokens that return no value (and instead revert or
         * throw on failure) are also supported, non-reverting calls are assumed to be
         * successful.
         * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
         * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
         */
        library SafeERC20 {
            using SafeMath for uint256;
            using Address for address;
        
            function safeTransfer(IERC20 token, address to, uint256 value) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
            }
        
            function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
            }
        
            /**
             * @dev Deprecated. This function has issues similar to the ones found in
             * {IERC20-approve}, and its usage is discouraged.
             *
             * Whenever possible, use {safeIncreaseAllowance} and
             * {safeDecreaseAllowance} instead.
             */
            function safeApprove(IERC20 token, address spender, uint256 value) internal {
                // safeApprove should only be called when setting an initial allowance,
                // or when resetting it to zero. To increase and decrease it, use
                // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                // solhint-disable-next-line max-line-length
                require((value == 0) || (token.allowance(address(this), spender) == 0),
                    "SafeERC20: approve from non-zero to non-zero allowance"
                );
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
            }
        
            function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                uint256 newAllowance = token.allowance(address(this), spender).add(value);
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
            }
        
            function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
            }
        
            /**
             * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
             * on the return value: the return value is optional (but if data is returned, it must not be false).
             * @param token The token targeted by the call.
             * @param data The call data (encoded using abi.encode or one of its variants).
             */
            function _callOptionalReturn(IERC20 token, bytes memory data) private {
                // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                // the target address contains contract code and also asserts for success in the low-level call.
        
                bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                if (returndata.length > 0) { // Return data is optional
                    // solhint-disable-next-line max-line-length
                    require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                }
            }
        }
        
        // File: solidity/contracts/converter/ConverterVersion.sol
        
        
        pragma solidity 0.6.12;
        
        contract ConverterVersion {
            uint16 public constant version = 46;
        }
        
        // File: solidity/contracts/utility/interfaces/IOwned.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Owned contract interface
        */
        interface IOwned {
            // this function isn't since the compiler emits automatically generated getter functions as external
            function owner() external view returns (address);
        
            function transferOwnership(address _newOwner) external;
        
            function acceptOwnership() external;
        }
        
        // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
        
        
        pragma solidity 0.6.12;
        
        
        /*
            Converter Anchor interface
        */
        interface IConverterAnchor is IOwned {
        
        }
        
        // File: solidity/contracts/converter/interfaces/IConverter.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /*
            Converter interface
        */
        interface IConverter is IOwned {
            function converterType() external pure returns (uint16);
        
            function anchor() external view returns (IConverterAnchor);
        
            function isActive() external view returns (bool);
        
            function targetAmountAndFee(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount
            ) external view returns (uint256, uint256);
        
            function convert(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount,
                address _trader,
                address payable _beneficiary
            ) external payable returns (uint256);
        
            function conversionFee() external view returns (uint32);
        
            function maxConversionFee() external view returns (uint32);
        
            function reserveBalance(IERC20 _reserveToken) external view returns (uint256);
        
            receive() external payable;
        
            function transferAnchorOwnership(address _newOwner) external;
        
            function acceptAnchorOwnership() external;
        
            function setConversionFee(uint32 _conversionFee) external;
        
            function addReserve(IERC20 _token, uint32 _weight) external;
        
            function transferReservesOnUpgrade(address _newConverter) external;
        
            function onUpgradeComplete() external;
        
            // deprecated, backward compatibility
            function token() external view returns (IConverterAnchor);
        
            function transferTokenOwnership(address _newOwner) external;
        
            function acceptTokenOwnership() external;
        
            function connectors(IERC20 _address)
                external
                view
                returns (
                    uint256,
                    uint32,
                    bool,
                    bool,
                    bool
                );
        
            function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256);
        
            function connectorTokens(uint256 _index) external view returns (IERC20);
        
            function connectorTokenCount() external view returns (uint16);
        
            /**
             * @dev triggered when the converter is activated
             *
             * @param _type        converter type
             * @param _anchor      converter anchor
             * @param _activated   true if the converter was activated, false if it was deactivated
             */
            event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
        
            /**
             * @dev triggered when a conversion between two tokens occurs
             *
             * @param _fromToken       source ERC20 token
             * @param _toToken         target ERC20 token
             * @param _trader          wallet that initiated the trade
             * @param _amount          input amount in units of the source token
             * @param _return          output amount minus conversion fee in units of the target token
             * @param _conversionFee   conversion fee in units of the target token
             */
            event Conversion(
                IERC20 indexed _fromToken,
                IERC20 indexed _toToken,
                address indexed _trader,
                uint256 _amount,
                uint256 _return,
                int256 _conversionFee
            );
        
            /**
             * @dev triggered when the rate between two tokens in the converter changes
             * note that the event might be dispatched for rate updates between any two tokens in the converter
             *
             * @param  _token1 address of the first token
             * @param  _token2 address of the second token
             * @param  _rateN  rate of 1 unit of `_token1` in `_token2` (numerator)
             * @param  _rateD  rate of 1 unit of `_token1` in `_token2` (denominator)
             */
            event TokenRateUpdate(IERC20 indexed _token1, IERC20 indexed _token2, uint256 _rateN, uint256 _rateD);
        
            /**
             * @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);
        }
        
        // File: solidity/contracts/converter/interfaces/IConverterUpgrader.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Converter Upgrader interface
        */
        interface IConverterUpgrader {
            function upgrade(bytes32 _version) external;
        
            function upgrade(uint16 _version) external;
        }
        
        // File: solidity/contracts/utility/interfaces/ITokenHolder.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        /*
            Token Holder interface
        */
        interface ITokenHolder is IOwned {
            receive() external payable;
        
            function withdrawTokens(
                IERC20 token,
                address payable to,
                uint256 amount
            ) external;
        
            function withdrawTokensMultiple(
                IERC20[] calldata tokens,
                address payable to,
                uint256[] calldata amounts
            ) external;
        }
        
        // File: solidity/contracts/INetworkSettings.sol
        
        
        pragma solidity 0.6.12;
        
        
        interface INetworkSettings {
            function networkFeeParams() external view returns (ITokenHolder, uint32);
        
            function networkFeeWallet() external view returns (ITokenHolder);
        
            function networkFee() external view returns (uint32);
        }
        
        // File: solidity/contracts/token/interfaces/IDSToken.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /*
            DSToken interface
        */
        interface IDSToken is IConverterAnchor, IERC20 {
            function issue(address _to, uint256 _amount) external;
        
            function destroy(address _from, uint256 _amount) external;
        }
        
        // File: solidity/contracts/utility/MathEx.sol
        
        
        pragma solidity 0.6.12;
        
        /**
         * @dev This library provides a set of complex math operations.
         */
        library MathEx {
            uint256 private constant MAX_EXP_BIT_LEN = 4;
            uint256 private constant MAX_EXP = 2**MAX_EXP_BIT_LEN - 1;
            uint256 private constant MAX_UINT128 = 2**128 - 1;
        
            /**
             * @dev returns the largest integer smaller than or equal to the square root of a positive integer
             *
             * @param _num a positive integer
             *
             * @return the largest integer smaller than or equal to the square root of the positive integer
             */
            function floorSqrt(uint256 _num) internal pure returns (uint256) {
                uint256 x = _num / 2 + 1;
                uint256 y = (x + _num / x) / 2;
                while (x > y) {
                    x = y;
                    y = (x + _num / x) / 2;
                }
                return x;
            }
        
            /**
             * @dev returns the smallest integer larger than or equal to the square root of a positive integer
             *
             * @param _num a positive integer
             *
             * @return the smallest integer larger than or equal to the square root of the positive integer
             */
            function ceilSqrt(uint256 _num) internal pure returns (uint256) {
                uint256 x = floorSqrt(_num);
                return x * x == _num ? x : x + 1;
            }
        
            /**
             * @dev computes a powered ratio
             *
             * @param _n   ratio numerator
             * @param _d   ratio denominator
             * @param _exp ratio exponent
             *
             * @return powered ratio's numerator and denominator
             */
            function poweredRatio(
                uint256 _n,
                uint256 _d,
                uint256 _exp
            ) internal pure returns (uint256, uint256) {
                require(_exp <= MAX_EXP, "ERR_EXP_TOO_LARGE");
        
                uint256[MAX_EXP_BIT_LEN] memory ns;
                uint256[MAX_EXP_BIT_LEN] memory ds;
        
                (ns[0], ds[0]) = reducedRatio(_n, _d, MAX_UINT128);
                for (uint256 i = 0; (_exp >> i) > 1; i++) {
                    (ns[i + 1], ds[i + 1]) = reducedRatio(ns[i] ** 2, ds[i] ** 2, MAX_UINT128);
                }
        
                uint256 n = 1;
                uint256 d = 1;
        
                for (uint256 i = 0; (_exp >> i) > 0; i++) {
                    if (((_exp >> i) & 1) > 0) {
                        (n, d) = reducedRatio(n * ns[i], d * ds[i], MAX_UINT128);
                    }
                }
        
                return (n, d);
            }
        
            /**
             * @dev computes a reduced-scalar ratio
             *
             * @param _n   ratio numerator
             * @param _d   ratio denominator
             * @param _max maximum desired scalar
             *
             * @return ratio's numerator and denominator
             */
            function reducedRatio(
                uint256 _n,
                uint256 _d,
                uint256 _max
            ) internal pure returns (uint256, uint256) {
                (uint256 n, uint256 d) = (_n, _d);
                if (n > _max || d > _max) {
                    (n, d) = normalizedRatio(n, d, _max);
                }
                if (n != d) {
                    return (n, d);
                }
                return (1, 1);
            }
        
            /**
             * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
             */
            function normalizedRatio(
                uint256 _a,
                uint256 _b,
                uint256 _scale
            ) internal pure returns (uint256, uint256) {
                if (_a <= _b) {
                    return accurateRatio(_a, _b, _scale);
                }
                (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
                return (x, y);
            }
        
            /**
             * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b".
             */
            function accurateRatio(
                uint256 _a,
                uint256 _b,
                uint256 _scale
            ) internal pure returns (uint256, uint256) {
                uint256 maxVal = uint256(-1) / _scale;
                if (_a > maxVal) {
                    uint256 c = _a / (maxVal + 1) + 1;
                    _a /= c; // we can now safely compute `_a * _scale`
                    _b /= c;
                }
                if (_a != _b) {
                    uint256 n = _a * _scale;
                    uint256 d = _a + _b; // can overflow
                    if (d >= _a) {
                        // no overflow in `_a + _b`
                        uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x`
                        uint256 y = _scale - x;
                        return (x, y);
                    }
                    if (n < _b - (_b - _a) / 2) {
                        return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b`
                    }
                    return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b`
                }
                return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function
            }
        
            /**
             * @dev computes the nearest integer to a given quotient without overflowing or underflowing.
             */
            function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
                return _n / _d + (_n % _d) / (_d - _d / 2);
            }
        
            /**
             * @dev returns the average number of decimal digits in a given list of positive integers
             *
             * @param _values  list of positive integers
             *
             * @return the average number of decimal digits in the given list of positive integers
             */
            function geometricMean(uint256[] memory _values) internal pure returns (uint256) {
                uint256 numOfDigits = 0;
                uint256 length = _values.length;
                for (uint256 i = 0; i < length; i++) {
                    numOfDigits += decimalLength(_values[i]);
                }
                return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1);
            }
        
            /**
             * @dev returns the number of decimal digits in a given positive integer
             *
             * @param _x   positive integer
             *
             * @return the number of decimal digits in the given positive integer
             */
            function decimalLength(uint256 _x) internal pure returns (uint256) {
                uint256 y = 0;
                for (uint256 x = _x; x > 0; x /= 10) {
                    y++;
                }
                return y;
            }
        
            /**
             * @dev returns the nearest integer to a given quotient
             * the computation is overflow-safe assuming that the input is sufficiently small
             *
             * @param _n   quotient numerator
             * @param _d   quotient denominator
             *
             * @return the nearest integer to the given quotient
             */
            function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) {
                return (_n + _d / 2) / _d;
            }
        
            /**
             * @dev returns the larger of two values
             *
             * @param _val1 the first value
             * @param _val2 the second value
             */
            function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) {
                return _val1 > _val2 ? _val1 : _val2;
            }
        }
        
        // File: solidity/contracts/utility/Owned.sol
        
        
        pragma solidity 0.6.12;
        
        
        /**
         * @dev This contract provides support and utilities for contract ownership.
         */
        contract Owned is IOwned {
            address public override 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 {
                _ownerOnly();
                _;
            }
        
            // error message binary size optimization
            function _ownerOnly() internal view {
                require(msg.sender == owner, "ERR_ACCESS_DENIED");
            }
        
            /**
             * @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 override ownerOnly {
                require(_newOwner != owner, "ERR_SAME_OWNER");
                newOwner = _newOwner;
            }
        
            /**
             * @dev used by a new owner to accept an ownership transfer
             */
            function acceptOwnership() public override {
                require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
                emit OwnerUpdate(owner, newOwner);
                owner = newOwner;
                newOwner = address(0);
            }
        }
        
        // File: solidity/contracts/utility/Utils.sol
        
        
        pragma solidity 0.6.12;
        
        
        /**
         * @dev Utilities & Common Modifiers
         */
        contract Utils {
            uint32 internal constant PPM_RESOLUTION = 1000000;
            IERC20 internal constant NATIVE_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
        
            // verifies that a value is greater than zero
            modifier greaterThanZero(uint256 _value) {
                _greaterThanZero(_value);
                _;
            }
        
            // error message binary size optimization
            function _greaterThanZero(uint256 _value) internal pure {
                require(_value > 0, "ERR_ZERO_VALUE");
            }
        
            // validates an address - currently only checks that it isn't null
            modifier validAddress(address _address) {
                _validAddress(_address);
                _;
            }
        
            // error message binary size optimization
            function _validAddress(address _address) internal pure {
                require(_address != address(0), "ERR_INVALID_ADDRESS");
            }
        
            // ensures that the portion is valid
            modifier validPortion(uint32 _portion) {
                _validPortion(_portion);
                _;
            }
        
            // error message binary size optimization
            function _validPortion(uint32 _portion) internal pure {
                require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
            }
        
            // validates an external address - currently only checks that it isn't null or this
            modifier validExternalAddress(address _address) {
                _validExternalAddress(_address);
                _;
            }
        
            // error message binary size optimization
            function _validExternalAddress(address _address) internal view {
                require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
            }
        
            // ensures that the fee is valid
            modifier validFee(uint32 fee) {
                _validFee(fee);
                _;
            }
        
            // error message binary size optimization
            function _validFee(uint32 fee) internal pure {
                require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE");
            }
        }
        
        // File: solidity/contracts/utility/interfaces/IContractRegistry.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Contract Registry interface
        */
        interface IContractRegistry {
            function addressOf(bytes32 _contractName) external view returns (address);
        }
        
        // File: solidity/contracts/utility/ContractRegistryClient.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /**
         * @dev This is the base contract for ContractRegistry clients.
         */
        contract ContractRegistryClient is Owned, Utils {
            bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
            bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
            bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
            bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
            bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
            bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
            bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
            bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
            bytes32 internal constant BNT_TOKEN = "BNTToken";
            bytes32 internal constant BANCOR_X = "BancorX";
            bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
            bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection";
            bytes32 internal constant NETWORK_SETTINGS = "NetworkSettings";
        
            IContractRegistry public registry; // address of the current contract-registry
            IContractRegistry public prevRegistry; // address of the previous contract-registry
            bool public onlyOwnerCanUpdateRegistry; // only an owner 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) {
                _only(_contractName);
                _;
            }
        
            // error message binary size optimization
            function _only(bytes32 _contractName) internal view {
                require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED");
            }
        
            /**
             * @dev initializes a new ContractRegistryClient instance
             *
             * @param  _registry   address of a contract-registry contract
             */
            constructor(IContractRegistry _registry) internal validAddress(address(_registry)) {
                registry = IContractRegistry(_registry);
                prevRegistry = IContractRegistry(_registry);
            }
        
            /**
             * @dev updates to the new contract-registry
             */
            function updateRegistry() public {
                // verify that this function is permitted
                require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
        
                // get the new contract-registry
                IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
        
                // verify that the new contract-registry is different and not zero
                require(newRegistry != registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY");
        
                // verify that the new contract-registry is pointing to a non-zero contract-registry
                require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
        
                // save a backup of the current contract-registry before replacing it
                prevRegistry = registry;
        
                // replace the current contract-registry with the new contract-registry
                registry = newRegistry;
            }
        
            /**
             * @dev restores the previous contract-registry
             */
            function restoreRegistry() public ownerOnly {
                // restore the previous contract-registry
                registry = prevRegistry;
            }
        
            /**
             * @dev restricts the permission to update the contract-registry
             *
             * @param _onlyOwnerCanUpdateRegistry  indicates whether or not permission is restricted to owner only
             */
            function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly {
                // change the permission to update the contract-registry
                onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
            }
        
            /**
             * @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: solidity/contracts/utility/ReentrancyGuard.sol
        
        
        pragma solidity 0.6.12;
        
        /**
         * @dev This contract provides protection against calling a function
         * (directly or indirectly) from within itself.
         */
        contract ReentrancyGuard {
            uint256 private constant UNLOCKED = 1;
            uint256 private constant LOCKED = 2;
        
            // LOCKED while protected code is being executed, UNLOCKED otherwise
            uint256 private state = UNLOCKED;
        
            /**
             * @dev ensures instantiation only by sub-contracts
             */
            constructor() internal {}
        
            // protects a function against reentrancy attacks
            modifier protected() {
                _protected();
                state = LOCKED;
                _;
                state = UNLOCKED;
            }
        
            // error message binary size optimization
            function _protected() internal view {
                require(state == UNLOCKED, "ERR_REENTRANCY");
            }
        }
        
        // File: solidity/contracts/utility/Time.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Time implementing contract
        */
        contract Time {
            /**
             * @dev returns the current time
             */
            function time() internal view virtual returns (uint256) {
                return block.timestamp;
            }
        }
        
        // File: solidity/contracts/converter/types/standard-pool/StandardPoolConverter.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        
        
        
        
        
        
        
        
        
        /**
         * @dev This contract is a specialized version of the converter, which is
         * optimized for a liquidity pool that has 2 reserves with 50%/50% weights.
         */
        contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time {
            using SafeMath for uint256;
            using SafeERC20 for IERC20;
            using MathEx for *;
        
            uint256 private constant MAX_UINT128 = 2**128 - 1;
            uint256 private constant MAX_UINT112 = 2**112 - 1;
            uint256 private constant MAX_UINT32 = 2**32 - 1;
            uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes;
        
            uint256 private __reserveBalances;
            uint256 private _reserveBalancesProduct;
            IERC20[] private __reserveTokens;
            mapping(IERC20 => uint256) private __reserveIds;
        
            IConverterAnchor public override anchor; // converter anchor contract
            uint32 public override maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000
            uint32 public override conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee
        
            // average rate details:
            // bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1
            // bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1
            // bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1
            // where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1
            uint256 public averageRateInfo;
        
            /**
             * @dev triggered after liquidity is added
             *
             * @param  _provider       liquidity provider
             * @param  _reserveToken   reserve token address
             * @param  _amount         reserve token amount
             * @param  _newBalance     reserve token new balance
             * @param  _newSupply      pool token new supply
             */
            event LiquidityAdded(
                address indexed _provider,
                IERC20 indexed _reserveToken,
                uint256 _amount,
                uint256 _newBalance,
                uint256 _newSupply
            );
        
            /**
             * @dev triggered after liquidity is removed
             *
             * @param  _provider       liquidity provider
             * @param  _reserveToken   reserve token address
             * @param  _amount         reserve token amount
             * @param  _newBalance     reserve token new balance
             * @param  _newSupply      pool token new supply
             */
            event LiquidityRemoved(
                address indexed _provider,
                IERC20 indexed _reserveToken,
                uint256 _amount,
                uint256 _newBalance,
                uint256 _newSupply
            );
        
            /**
             * @dev initializes a new StandardPoolConverter instance
             *
             * @param  _anchor             anchor governed by the converter
             * @param  _registry           address of a contract registry contract
             * @param  _maxConversionFee   maximum conversion fee, represented in ppm
             */
            constructor(
                IConverterAnchor _anchor,
                IContractRegistry _registry,
                uint32 _maxConversionFee
            ) public ContractRegistryClient(_registry) validAddress(address(_anchor)) validConversionFee(_maxConversionFee) {
                anchor = _anchor;
                maxConversionFee = _maxConversionFee;
            }
        
            // ensures that the converter is active
            modifier active() {
                _active();
                _;
            }
        
            // error message binary size optimization
            function _active() internal view {
                require(isActive(), "ERR_INACTIVE");
            }
        
            // ensures that the converter is not active
            modifier inactive() {
                _inactive();
                _;
            }
        
            // error message binary size optimization
            function _inactive() internal view {
                require(!isActive(), "ERR_ACTIVE");
            }
        
            // validates a reserve token address - verifies that the address belongs to one of the reserve tokens
            modifier validReserve(IERC20 _address) {
                _validReserve(_address);
                _;
            }
        
            // error message binary size optimization
            function _validReserve(IERC20 _address) internal view {
                require(__reserveIds[_address] != 0, "ERR_INVALID_RESERVE");
            }
        
            // validates conversion fee
            modifier validConversionFee(uint32 _conversionFee) {
                _validConversionFee(_conversionFee);
                _;
            }
        
            // error message binary size optimization
            function _validConversionFee(uint32 _conversionFee) internal pure {
                require(_conversionFee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE");
            }
        
            // validates reserve weight
            modifier validReserveWeight(uint32 _weight) {
                _validReserveWeight(_weight);
                _;
            }
        
            // error message binary size optimization
            function _validReserveWeight(uint32 _weight) internal pure {
                require(_weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT");
            }
        
            /**
             * @dev returns the converter type
             *
             * @return see the converter types in the the main contract doc
             */
            function converterType() public pure virtual override returns (uint16) {
                return 3;
            }
        
            /**
             * @dev deposits ether
             * can only be called if the converter has an ETH reserve
             */
            receive() external payable override(IConverter) validReserve(NATIVE_TOKEN_ADDRESS) {}
        
            /**
             * @dev checks whether or not the converter version is 28 or higher
             *
             * @return true, since the converter version is 28 or higher
             */
            function isV28OrHigher() public pure returns (bool) {
                return true;
            }
        
            /**
             * @dev returns true if the converter is active, false otherwise
             *
             * @return true if the converter is active, false otherwise
             */
            function isActive() public view virtual override returns (bool) {
                return anchor.owner() == address(this);
            }
        
            /**
             * @dev transfers the anchor ownership
             * the new owner needs to accept the transfer
             * can only be called by the converter upgrader while the upgrader is the owner
             * note that prior to version 28, you should use 'transferAnchorOwnership' instead
             *
             * @param _newOwner    new token owner
             */
            function transferAnchorOwnership(address _newOwner) public override ownerOnly only(CONVERTER_UPGRADER) {
                anchor.transferOwnership(_newOwner);
            }
        
            /**
             * @dev accepts ownership of the anchor after an ownership transfer
             * most converters are also activated as soon as they accept the anchor ownership
             * can only be called by the contract owner
             * note that prior to version 28, you should use 'acceptTokenOwnership' instead
             */
            function acceptAnchorOwnership() public virtual override ownerOnly {
                // verify the the converter has exactly two reserves
                require(reserveTokenCount() == 2, "ERR_INVALID_RESERVE_COUNT");
                anchor.acceptOwnership();
                syncReserveBalances(0);
                emit Activation(converterType(), anchor, true);
            }
        
            /**
             * @dev updates the current conversion fee
             * can only be called by the contract owner
             *
             * @param _conversionFee new conversion fee, represented in ppm
             */
            function setConversionFee(uint32 _conversionFee) public override ownerOnly {
                require(_conversionFee <= maxConversionFee, "ERR_INVALID_CONVERSION_FEE");
                emit ConversionFeeUpdate(conversionFee, _conversionFee);
                conversionFee = _conversionFee;
            }
        
            /**
             * @dev transfers reserve balances to a new converter during an upgrade
             * can only be called by the converter upgraded which should be set at its owner
             *
             * @param _newConverter address of the converter to receive the new amount
             */
            function transferReservesOnUpgrade(address _newConverter)
                external
                override
                protected
                ownerOnly
                only(CONVERTER_UPGRADER)
            {
                uint256 reserveCount = __reserveTokens.length;
                for (uint256 i = 0; i < reserveCount; ++i) {
                    IERC20 reserveToken = __reserveTokens[i];
        
                    uint256 amount;
                    if (reserveToken == NATIVE_TOKEN_ADDRESS) {
                        amount = address(this).balance;
                    } else {
                        amount = reserveToken.balanceOf(address(this));
                    }
        
                    safeTransfer(reserveToken, _newConverter, amount);
        
                    syncReserveBalance(reserveToken);
                }
            }
        
            /**
             * @dev upgrades the converter to the latest version
             * can only be called by the owner
             * note that the owner needs to call acceptOwnership on the new converter after the upgrade
             */
            function upgrade() public ownerOnly {
                IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER));
        
                // trigger de-activation event
                emit Activation(converterType(), anchor, false);
        
                transferOwnership(address(converterUpgrader));
                converterUpgrader.upgrade(version);
                acceptOwnership();
            }
        
            /**
             * @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic
             */
            function onUpgradeComplete()
                external
                override
                protected
                ownerOnly
                only(CONVERTER_UPGRADER)
            {
                (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
                _reserveBalancesProduct = reserveBalance0 * reserveBalance1;
            }
        
            /**
             * @dev returns the number of reserve tokens
             * 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 returns the array of reserve tokens
             *
             * @return array of reserve tokens
             */
            function reserveTokens() public view returns (IERC20[] memory) {
                return __reserveTokens;
            }
        
            /**
             * @dev defines a new reserve token for the converter
             * can only be called by the owner while the converter is inactive
             *
             * @param _token   address of the reserve token
             * @param _weight  reserve weight, represented in ppm, 1-1000000
             */
            function addReserve(IERC20 _token, uint32 _weight)
                public
                virtual
                override
                ownerOnly
                inactive
                validExternalAddress(address(_token))
                validReserveWeight(_weight)
            {
                // validate input
                require(address(_token) != address(anchor) && __reserveIds[_token] == 0, "ERR_INVALID_RESERVE");
                require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT");
        
                __reserveTokens.push(_token);
                __reserveIds[_token] = __reserveTokens.length;
            }
        
            /**
             * @dev returns the reserve's weight
             * added in version 28
             *
             * @param _reserveToken    reserve token contract address
             *
             * @return reserve weight
             */
            function reserveWeight(IERC20 _reserveToken) public view validReserve(_reserveToken) returns (uint32) {
                return PPM_RESOLUTION / 2;
            }
        
            /**
             * @dev returns the balance of a given reserve token
             *
             * @param _reserveToken    reserve token contract address
             *
             * @return the balance of the given reserve token
             */
            function reserveBalance(IERC20 _reserveToken) public view override returns (uint256) {
                uint256 reserveId = __reserveIds[_reserveToken];
                require(reserveId != 0, "ERR_INVALID_RESERVE");
                return reserveBalance(reserveId);
            }
        
            /**
             * @dev returns the balances of both reserve tokens
             *
             * @return the balances of both reserve tokens
             */
            function reserveBalances() public view returns (uint256, uint256) {
                return reserveBalances(1, 2);
            }
        
            /**
             * @dev syncs all stored reserve balances
             */
            function syncReserveBalances() external {
                syncReserveBalances(0);
            }
        
            /**
             * @dev calculates the accumulated network fee and transfers it to the network fee wallet
             */
            function processNetworkFees() external protected {
                (uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0);
                _reserveBalancesProduct = reserveBalance0 * reserveBalance1;
            }
        
            /**
             * @dev calculates the accumulated network fee and transfers it to the network fee wallet
             *
             * @param _value amount of ether to exclude from the ether reserve balance (if relevant)
             *
             * @return new reserve balances
             */
            function processNetworkFees(uint256 _value) internal returns (uint256, uint256) {
                syncReserveBalances(_value);
                (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
                (ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
                reserveBalance0 -= fee0;
                reserveBalance1 -= fee1;
                setReserveBalances(1, 2, reserveBalance0, reserveBalance1);
                safeTransfer(__reserveTokens[0], address(wallet), fee0);
                safeTransfer(__reserveTokens[1], address(wallet), fee1);
                return (reserveBalance0, reserveBalance1);
            }
        
            /**
             * @dev returns the reserve balances of the given reserve tokens minus their corresponding fees
             *
             * @param _reserveTokens reserve tokens
             *
             * @return reserve balances minus their corresponding fees
             */
            function baseReserveBalances(IERC20[] memory _reserveTokens) internal view returns (uint256[2] memory) {
                uint256 reserveId0 = __reserveIds[_reserveTokens[0]];
                uint256 reserveId1 = __reserveIds[_reserveTokens[1]];
                (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1);
                (, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
                return [reserveBalance0 - fee0, reserveBalance1 - fee1];
            }
        
            /**
             * @dev converts a specific amount of source tokens to target tokens
             * can only be called by the bancor network contract
             *
             * @param _sourceToken source ERC20 token
             * @param _targetToken target ERC20 token
             * @param _amount      amount of tokens to convert (in units of the source token)
             * @param _trader      address of the caller who executed the conversion
             * @param _beneficiary wallet to receive the conversion result
             *
             * @return amount of tokens received (in units of the target token)
             */
            function convert(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount,
                address _trader,
                address payable _beneficiary
            ) public payable override protected only(BANCOR_NETWORK) returns (uint256) {
                // validate input
                require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
        
                return doConvert(_sourceToken, _targetToken, _amount, _trader, _beneficiary);
            }
        
            /**
             * @dev returns the conversion fee for a given target amount
             *
             * @param _targetAmount  target amount
             *
             * @return conversion fee
             */
            function calculateFee(uint256 _targetAmount) internal view returns (uint256) {
                return _targetAmount.mul(conversionFee) / PPM_RESOLUTION;
            }
        
            /**
             * @dev returns the conversion fee taken from a given target amount
             *
             * @param _targetAmount  target amount
             *
             * @return conversion fee
             */
            function calculateFeeInv(uint256 _targetAmount) internal view returns (uint256) {
                return _targetAmount.mul(conversionFee).div(PPM_RESOLUTION - conversionFee);
            }
        
            /**
             * @dev loads the stored reserve balance for a given reserve id
             *
             * @param _reserveId   reserve id
             */
            function reserveBalance(uint256 _reserveId) internal view returns (uint256) {
                return decodeReserveBalance(__reserveBalances, _reserveId);
            }
        
            /**
             * @dev loads the stored reserve balances
             *
             * @param _sourceId    source reserve id
             * @param _targetId    target reserve id
             */
            function reserveBalances(uint256 _sourceId, uint256 _targetId) internal view returns (uint256, uint256) {
                require((_sourceId == 1 && _targetId == 2) || (_sourceId == 2 && _targetId == 1), "ERR_INVALID_RESERVES");
                return decodeReserveBalances(__reserveBalances, _sourceId, _targetId);
            }
        
            /**
             * @dev stores the stored reserve balance for a given reserve id
             *
             * @param _reserveId       reserve id
             * @param _reserveBalance  reserve balance
             */
            function setReserveBalance(uint256 _reserveId, uint256 _reserveBalance) internal {
                require(_reserveBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
                uint256 otherBalance = decodeReserveBalance(__reserveBalances, 3 - _reserveId);
                __reserveBalances = encodeReserveBalances(_reserveBalance, _reserveId, otherBalance, 3 - _reserveId);
            }
        
            /**
             * @dev stores the stored reserve balances
             *
             * @param _sourceId        source reserve id
             * @param _targetId        target reserve id
             * @param _sourceBalance   source reserve balance
             * @param _targetBalance   target reserve balance
             */
            function setReserveBalances(
                uint256 _sourceId,
                uint256 _targetId,
                uint256 _sourceBalance,
                uint256 _targetBalance
            ) internal {
                require(_sourceBalance <= MAX_UINT128 && _targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
                __reserveBalances = encodeReserveBalances(_sourceBalance, _sourceId, _targetBalance, _targetId);
            }
        
            /**
             * @dev syncs the stored reserve balance for a given reserve with the real reserve balance
             *
             * @param _reserveToken    address of the reserve token
             */
            function syncReserveBalance(IERC20 _reserveToken) internal {
                uint256 reserveId = __reserveIds[_reserveToken];
                uint256 balance =
                    _reserveToken == NATIVE_TOKEN_ADDRESS ? address(this).balance : _reserveToken.balanceOf(address(this));
                setReserveBalance(reserveId, balance);
            }
        
            /**
             * @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant)
             *
             * @param _value   amount of ether to exclude from the ether reserve balance (if relevant)
             */
            function syncReserveBalances(uint256 _value) internal {
                IERC20 _reserveToken0 = __reserveTokens[0];
                IERC20 _reserveToken1 = __reserveTokens[1];
                uint256 balance0 =
                    _reserveToken0 == NATIVE_TOKEN_ADDRESS
                        ? address(this).balance - _value
                        : _reserveToken0.balanceOf(address(this));
                uint256 balance1 =
                    _reserveToken1 == NATIVE_TOKEN_ADDRESS
                        ? address(this).balance - _value
                        : _reserveToken1.balanceOf(address(this));
                setReserveBalances(1, 2, balance0, balance1);
            }
        
            /**
             * @dev helper, dispatches the Conversion event
             *
             * @param _sourceToken     source ERC20 token
             * @param _targetToken     target ERC20 token
             * @param _trader          address of the caller who executed the conversion
             * @param _amount          amount purchased/sold (in the source token)
             * @param _returnAmount    amount returned (in the target token)
             */
            function dispatchConversionEvent(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                address _trader,
                uint256 _amount,
                uint256 _returnAmount,
                uint256 _feeAmount
            ) internal {
                emit Conversion(_sourceToken, _targetToken, _trader, _amount, _returnAmount, int256(_feeAmount));
            }
        
            /**
             * @dev returns the expected amount and expected fee for converting one reserve to another
             *
             * @param _sourceToken address of the source reserve token contract
             * @param _targetToken address of the target reserve token contract
             * @param _amount      amount of source reserve tokens converted
             *
             * @return expected amount in units of the target reserve token
             * @return expected fee in units of the target reserve token
             */
            function targetAmountAndFee(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount
            ) public view virtual override active returns (uint256, uint256) {
                uint256 sourceId = __reserveIds[_sourceToken];
                uint256 targetId = __reserveIds[_targetToken];
        
                (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
        
                return targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
            }
        
            /**
             * @dev returns the expected amount and expected fee for converting one reserve to another
             *
             * @param _sourceBalance    balance in the source reserve token contract
             * @param _targetBalance    balance in the target reserve token contract
             * @param _amount           amount of source reserve tokens converted
             *
             * @return expected amount in units of the target reserve token
             * @return expected fee in units of the target reserve token
             */
            function targetAmountAndFee(
                IERC20, /* _sourceToken */
                IERC20, /* _targetToken */
                uint256 _sourceBalance,
                uint256 _targetBalance,
                uint256 _amount
            ) internal view virtual returns (uint256, uint256) {
                uint256 amount = crossReserveTargetAmount(_sourceBalance, _targetBalance, _amount);
        
                uint256 fee = calculateFee(amount);
        
                return (amount - fee, fee);
            }
        
            /**
             * @dev returns the required amount and expected fee for converting one reserve to another
             *
             * @param _sourceToken address of the source reserve token contract
             * @param _targetToken address of the target reserve token contract
             * @param _amount      amount of target reserve tokens desired
             *
             * @return required amount in units of the source reserve token
             * @return expected fee in units of the target reserve token
             */
            function sourceAmountAndFee(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount
            ) public view virtual active returns (uint256, uint256) {
                uint256 sourceId = __reserveIds[_sourceToken];
                uint256 targetId = __reserveIds[_targetToken];
        
                (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
        
                uint256 fee = calculateFeeInv(_amount);
        
                uint256 amount = crossReserveSourceAmount(sourceBalance, targetBalance, _amount.add(fee));
        
                return (amount, fee);
            }
        
            /**
             * @dev converts a specific amount of source tokens to target tokens
             *
             * @param _sourceToken source ERC20 token
             * @param _targetToken target ERC20 token
             * @param _amount      amount of tokens to convert (in units of the source token)
             * @param _trader      address of the caller who executed the conversion
             * @param _beneficiary wallet to receive the conversion result
             *
             * @return amount of tokens received (in units of the target token)
             */
            function doConvert(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount,
                address _trader,
                address payable _beneficiary
            ) internal returns (uint256) {
                // update the recent average rate
                updateRecentAverageRate();
        
                uint256 sourceId = __reserveIds[_sourceToken];
                uint256 targetId = __reserveIds[_targetToken];
        
                (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
        
                // get the target amount minus the conversion fee and the conversion fee
                (uint256 amount, uint256 fee) =
                    targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
        
                // ensure that the trade gives something in return
                require(amount != 0, "ERR_ZERO_TARGET_AMOUNT");
        
                // ensure that the trade won't deplete the reserve balance
                assert(amount < targetBalance);
        
                // ensure that the input amount was already deposited
                uint256 actualSourceBalance;
                if (_sourceToken == NATIVE_TOKEN_ADDRESS) {
                    actualSourceBalance = address(this).balance;
                    require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
                } else {
                    actualSourceBalance = _sourceToken.balanceOf(address(this));
                    require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= _amount, "ERR_INVALID_AMOUNT");
                }
        
                // sync the reserve balances
                setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - amount);
        
                // transfer funds to the beneficiary in the to reserve token
                safeTransfer(_targetToken, _beneficiary, amount);
        
                // dispatch the conversion event
                dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
        
                // dispatch rate updates
                dispatchTokenRateUpdateEvents(_sourceToken, _targetToken, actualSourceBalance, targetBalance - amount);
        
                return amount;
            }
        
            /**
             * @dev returns the recent average rate of 1 `_token` in the other reserve token units
             *
             * @param _token   token to get the rate for
             *
             * @return recent average rate between the reserves (numerator)
             * @return recent average rate between the reserves (denominator)
             */
            function recentAverageRate(IERC20 _token) external view validReserve(_token) returns (uint256, uint256) {
                // get the recent average rate of reserve 0
                uint256 rate = calcRecentAverageRate(averageRateInfo);
        
                uint256 rateN = decodeAverageRateN(rate);
                uint256 rateD = decodeAverageRateD(rate);
        
                if (_token == __reserveTokens[0]) {
                    return (rateN, rateD);
                }
        
                return (rateD, rateN);
            }
        
            /**
             * @dev updates the recent average rate if needed
             */
            function updateRecentAverageRate() internal {
                uint256 averageRateInfo1 = averageRateInfo;
                uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1);
                if (averageRateInfo1 != averageRateInfo2) {
                    averageRateInfo = averageRateInfo2;
                }
            }
        
            /**
             * @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units
             *
             * @param _averageRateInfo a local copy of the `averageRateInfo` state-variable
             *
             * @return recent average rate between the reserves
             */
            function calcRecentAverageRate(uint256 _averageRateInfo) internal view returns (uint256) {
                // get the previous average rate and its update-time
                uint256 prevAverageRateT = decodeAverageRateT(_averageRateInfo);
                uint256 prevAverageRateN = decodeAverageRateN(_averageRateInfo);
                uint256 prevAverageRateD = decodeAverageRateD(_averageRateInfo);
        
                // get the elapsed time since the previous average rate was calculated
                uint256 currentTime = time();
                uint256 timeElapsed = currentTime - prevAverageRateT;
        
                // if the previous average rate was calculated in the current block, the average rate remains unchanged
                if (timeElapsed == 0) {
                    return _averageRateInfo;
                }
        
                // get the current rate between the reserves
                (uint256 currentRateD, uint256 currentRateN) = reserveBalances();
        
                // if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate
                if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) {
                    (currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112);
                    return encodeAverageRateInfo(currentTime, currentRateN, currentRateD);
                }
        
                uint256 x = prevAverageRateD.mul(currentRateN);
                uint256 y = prevAverageRateN.mul(currentRateD);
        
                // since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath:
                uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed));
                uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD);
        
                (newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112);
                return encodeAverageRateInfo(currentTime, newRateN, newRateD);
            }
        
            /**
             * @dev increases the pool's liquidity and mints new shares in the pool to the caller
             *
             * @param _reserveTokens   address of each reserve token
             * @param _reserveAmounts  amount of each reserve token
             * @param _minReturn       token minimum return-amount
             *
             * @return amount of pool tokens issued
             */
            function addLiquidity(
                IERC20[] memory _reserveTokens,
                uint256[] memory _reserveAmounts,
                uint256 _minReturn
            ) public payable protected active returns (uint256) {
                // verify the user input
                verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn);
        
                // if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH
                for (uint256 i = 0; i < 2; i++) {
                    if (_reserveTokens[i] == NATIVE_TOKEN_ADDRESS) {
                        require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH");
                    }
                }
        
                // if the input value of ETH is larger than zero, then verify that one of the reserves is ETH
                if (msg.value > 0) {
                    require(__reserveIds[NATIVE_TOKEN_ADDRESS] != 0, "ERR_NO_ETH_RESERVE");
                }
        
                // save a local copy of the pool token
                IDSToken poolToken = IDSToken(address(anchor));
        
                // get the total supply
                uint256 totalSupply = poolToken.totalSupply();
        
                uint256[2] memory prevReserveBalances;
                uint256[2] memory newReserveBalances;
        
                // process the network fees and get the reserve balances
                (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value);
        
                uint256 amount;
                uint256[2] memory reserveAmounts;
        
                // calculate the amount of pool tokens to mint for the caller
                // and the amount of reserve tokens to transfer from the caller
                if (totalSupply == 0) {
                    amount = MathEx.geometricMean(_reserveAmounts);
                    reserveAmounts[0] = _reserveAmounts[0];
                    reserveAmounts[1] = _reserveAmounts[1];
                } else {
                    (amount, reserveAmounts) = addLiquidityAmounts(
                        _reserveTokens,
                        _reserveAmounts,
                        prevReserveBalances,
                        totalSupply
                    );
                }
        
                uint256 newPoolTokenSupply = totalSupply.add(amount);
                for (uint256 i = 0; i < 2; i++) {
                    IERC20 reserveToken = _reserveTokens[i];
                    uint256 reserveAmount = reserveAmounts[i];
                    require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT");
                    assert(reserveAmount <= _reserveAmounts[i]);
        
                    // transfer each one of the reserve amounts from the user to the pool
                    if (reserveToken != NATIVE_TOKEN_ADDRESS) {
                        // ETH has already been transferred as part of the transaction
                        reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount);
                    } else if (_reserveAmounts[i] > reserveAmount) {
                        // transfer the extra amount of ETH back to the user
                        msg.sender.transfer(_reserveAmounts[i] - reserveAmount);
                    }
        
                    // save the new reserve balance
                    newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount);
        
                    emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
        
                    // dispatch the `TokenRateUpdate` event for the pool token
                    emit TokenRateUpdate(poolToken, reserveToken, newReserveBalances[i], newPoolTokenSupply);
                }
        
                // set the reserve balances
                setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
        
                // set the reserve balances product
                _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
        
                // verify that the equivalent amount of tokens is equal to or larger than the user's expectation
                require(amount >= _minReturn, "ERR_RETURN_TOO_LOW");
        
                // issue the tokens to the user
                poolToken.issue(msg.sender, amount);
        
                // return the amount of pool tokens issued
                return amount;
            }
        
            /**
             * @dev get the amount of pool tokens to mint for the caller
             * and the amount of reserve tokens to transfer from the caller
             *
             * @param _reserveAmounts   amount of each reserve token
             * @param _reserveBalances  balance of each reserve token
             * @param _totalSupply      total supply of pool tokens
             *
             * @return amount of pool tokens to mint for the caller
             * @return amount of reserve tokens to transfer from the caller
             */
            function addLiquidityAmounts(
                IERC20[] memory, /* _reserveTokens */
                uint256[] memory _reserveAmounts,
                uint256[2] memory _reserveBalances,
                uint256 _totalSupply
            ) internal view virtual returns (uint256, uint256[2] memory) {
                this;
        
                uint256 index =
                    _reserveAmounts[0].mul(_reserveBalances[1]) < _reserveAmounts[1].mul(_reserveBalances[0]) ? 0 : 1;
                uint256 amount = fundSupplyAmount(_totalSupply, _reserveBalances[index], _reserveAmounts[index]);
        
                uint256[2] memory reserveAmounts =
                    [fundCost(_totalSupply, _reserveBalances[0], amount), fundCost(_totalSupply, _reserveBalances[1], amount)];
        
                return (amount, reserveAmounts);
            }
        
            /**
             * @dev decreases the pool's liquidity and burns the caller's shares in the pool
             *
             * @param _amount                  token amount
             * @param _reserveTokens           address of each reserve token
             * @param _reserveMinReturnAmounts minimum return-amount of each reserve token
             *
             * @return the amount of each reserve token granted for the given amount of pool tokens
             */
            function removeLiquidity(
                uint256 _amount,
                IERC20[] memory _reserveTokens,
                uint256[] memory _reserveMinReturnAmounts
            ) public protected active returns (uint256[] memory) {
                // verify the user input
                bool inputRearranged = verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);
        
                // save a local copy of the pool token
                IDSToken poolToken = IDSToken(address(anchor));
        
                // get the total supply BEFORE destroying the user tokens
                uint256 totalSupply = poolToken.totalSupply();
        
                // destroy the user tokens
                poolToken.destroy(msg.sender, _amount);
        
                uint256 newPoolTokenSupply = totalSupply.sub(_amount);
        
                uint256[2] memory prevReserveBalances;
                uint256[2] memory newReserveBalances;
        
                // process the network fees and get the reserve balances
                (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0);
        
                uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, totalSupply, prevReserveBalances);
        
                for (uint256 i = 0; i < 2; i++) {
                    IERC20 reserveToken = _reserveTokens[i];
                    uint256 reserveAmount = reserveAmounts[i];
                    require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
        
                    // save the new reserve balance
                    newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount);
        
                    // transfer each one of the reserve amounts from the pool to the user
                    safeTransfer(reserveToken, msg.sender, reserveAmount);
        
                    emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
        
                    // dispatch the `TokenRateUpdate` event for the pool token
                    emit TokenRateUpdate(poolToken, reserveToken, newReserveBalances[i], newPoolTokenSupply);
                }
        
                // set the reserve balances
                setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
        
                // set the reserve balances product
                _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
        
                if (inputRearranged) {
                    uint256 tempReserveAmount = reserveAmounts[0];
                    reserveAmounts[0] = reserveAmounts[1];
                    reserveAmounts[1] = tempReserveAmount;
                }
        
                // return the amount of each reserve token granted for the given amount of pool tokens
                return reserveAmounts;
            }
        
            /**
             * @dev given the amount of one of the reserve tokens to add liquidity of,
             * returns the required amount of each one of the other reserve tokens
             * since an empty pool can be funded with any list of non-zero input amounts,
             * this function assumes that the pool is not empty (has already been funded)
             *
             * @param _reserveTokens       address of each reserve token
             * @param _reserveTokenIndex   index of the relevant reserve token
             * @param _reserveAmount       amount of the relevant reserve token
             *
             * @return the required amount of each one of the reserve tokens
             */
            function addLiquidityCost(
                IERC20[] memory _reserveTokens,
                uint256 _reserveTokenIndex,
                uint256 _reserveAmount
            ) public view returns (uint256[] memory) {
                uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
                uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
                uint256 amount = fundSupplyAmount(totalSupply, baseBalances[_reserveTokenIndex], _reserveAmount);
        
                uint256[] memory reserveAmounts = new uint256[](2);
                reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], amount);
                reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], amount);
                return reserveAmounts;
            }
        
            /**
             * @dev returns the amount of pool tokens entitled for given amounts of reserve tokens
             * since an empty pool can be funded with any list of non-zero input amounts,
             * this function assumes that the pool is not empty (has already been funded)
             *
             * @param _reserveTokens   address of each reserve token
             * @param _reserveAmounts  amount of each reserve token
             *
             * @return the amount of pool tokens entitled for the given amounts of reserve tokens
             */
            function addLiquidityReturn(IERC20[] memory _reserveTokens, uint256[] memory _reserveAmounts)
                public
                view
                returns (uint256)
            {
                uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
                uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
                (uint256 amount, ) = addLiquidityAmounts(_reserveTokens, _reserveAmounts, baseBalances, totalSupply);
                return amount;
            }
        
            /**
             * @dev returns the amount of each reserve token entitled for a given amount of pool tokens
             *
             * @param _amount          amount of pool tokens
             * @param _reserveTokens   address of each reserve token
             *
             * @return the amount of each reserve token entitled for the given amount of pool tokens
             */
            function removeLiquidityReturn(uint256 _amount, IERC20[] memory _reserveTokens)
                public
                view
                returns (uint256[] memory)
            {
                uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
                uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
                return removeLiquidityReserveAmounts(_amount, totalSupply, baseBalances);
            }
        
            /**
             * @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
             * we take this input in order to allow specifying the corresponding reserve amounts in any order
             * this function rearranges the input arrays according to the converter's array of reserve tokens
             *
             * @param _reserveTokens   array of reserve tokens
             * @param _reserveAmounts  array of reserve amounts
             * @param _amount          token amount
             *
             * @return true if the function has rearranged the input arrays; false otherwise
             */
            function verifyLiquidityInput(
                IERC20[] memory _reserveTokens,
                uint256[] memory _reserveAmounts,
                uint256 _amount
            ) private view returns (bool) {
                require(validReserveAmounts(_reserveAmounts) && _amount > 0, "ERR_ZERO_AMOUNT");
        
                uint256 reserve0Id = __reserveIds[_reserveTokens[0]];
                uint256 reserve1Id = __reserveIds[_reserveTokens[1]];
        
                if (reserve0Id == 2 && reserve1Id == 1) {
                    IERC20 tempReserveToken = _reserveTokens[0];
                    _reserveTokens[0] = _reserveTokens[1];
                    _reserveTokens[1] = tempReserveToken;
                    uint256 tempReserveAmount = _reserveAmounts[0];
                    _reserveAmounts[0] = _reserveAmounts[1];
                    _reserveAmounts[1] = tempReserveAmount;
                    return true;
                }
        
                require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE");
                return false;
            }
        
            /**
             * @dev checks whether or not both reserve amounts are larger than zero
             *
             * @param _reserveAmounts  array of reserve amounts
             *
             * @return true if both reserve amounts are larger than zero; false otherwise
             */
            function validReserveAmounts(uint256[] memory _reserveAmounts) internal pure virtual returns (bool) {
                return _reserveAmounts[0] > 0 && _reserveAmounts[1] > 0;
            }
        
            /**
             * @dev returns the amount of each reserve token entitled for a given amount of pool tokens
             *
             * @param _amount          amount of pool tokens
             * @param _totalSupply     total supply of pool tokens
             * @param _reserveBalances balance of each reserve token
             *
             * @return the amount of each reserve token entitled for the given amount of pool tokens
             */
            function removeLiquidityReserveAmounts(
                uint256 _amount,
                uint256 _totalSupply,
                uint256[2] memory _reserveBalances
            ) private pure returns (uint256[] memory) {
                uint256[] memory reserveAmounts = new uint256[](2);
                reserveAmounts[0] = liquidateReserveAmount(_totalSupply, _reserveBalances[0], _amount);
                reserveAmounts[1] = liquidateReserveAmount(_totalSupply, _reserveBalances[1], _amount);
                return reserveAmounts;
            }
        
            /**
             * @dev dispatches token rate update events for the reserve tokens and the pool token
             *
             * @param _sourceToken     address of the source reserve token
             * @param _targetToken     address of the target reserve token
             * @param _sourceBalance   balance of the source reserve token
             * @param _targetBalance   balance of the target reserve token
             */
            function dispatchTokenRateUpdateEvents(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _sourceBalance,
                uint256 _targetBalance
            ) private {
                // save a local copy of the pool token
                IDSToken poolToken = IDSToken(address(anchor));
        
                // get the total supply of pool tokens
                uint256 poolTokenSupply = poolToken.totalSupply();
        
                // dispatch token rate update event for the reserve tokens
                emit TokenRateUpdate(_sourceToken, _targetToken, _targetBalance, _sourceBalance);
        
                // dispatch token rate update events for the pool token
                emit TokenRateUpdate(poolToken, _sourceToken, _sourceBalance, poolTokenSupply);
                emit TokenRateUpdate(poolToken, _targetToken, _targetBalance, poolTokenSupply);
            }
        
            function encodeReserveBalance(uint256 _balance, uint256 _id) private pure returns (uint256) {
                assert(_balance <= MAX_UINT128 && (_id == 1 || _id == 2));
                return _balance << ((_id - 1) * 128);
            }
        
            function decodeReserveBalance(uint256 _balances, uint256 _id) private pure returns (uint256) {
                assert(_id == 1 || _id == 2);
                return (_balances >> ((_id - 1) * 128)) & MAX_UINT128;
            }
        
            function encodeReserveBalances(
                uint256 _balance0,
                uint256 _id0,
                uint256 _balance1,
                uint256 _id1
            ) private pure returns (uint256) {
                return encodeReserveBalance(_balance0, _id0) | encodeReserveBalance(_balance1, _id1);
            }
        
            function decodeReserveBalances(
                uint256 _balances,
                uint256 _id0,
                uint256 _id1
            ) private pure returns (uint256, uint256) {
                return (decodeReserveBalance(_balances, _id0), decodeReserveBalance(_balances, _id1));
            }
        
            function encodeAverageRateInfo(
                uint256 _averageRateT,
                uint256 _averageRateN,
                uint256 _averageRateD
            ) private pure returns (uint256) {
                assert(_averageRateT <= MAX_UINT32 && _averageRateN <= MAX_UINT112 && _averageRateD <= MAX_UINT112);
                return (_averageRateT << 224) | (_averageRateN << 112) | _averageRateD;
            }
        
            function decodeAverageRateT(uint256 _averageRateInfo) private pure returns (uint256) {
                return _averageRateInfo >> 224;
            }
        
            function decodeAverageRateN(uint256 _averageRateInfo) private pure returns (uint256) {
                return (_averageRateInfo >> 112) & MAX_UINT112;
            }
        
            function decodeAverageRateD(uint256 _averageRateInfo) private pure returns (uint256) {
                return _averageRateInfo & MAX_UINT112;
            }
        
            /**
             * @dev returns the largest integer smaller than or equal to the square root of a given value
             *
             * @param x the given value
             *
             * @return the largest integer smaller than or equal to the square root of the given value
             */
            function floorSqrt(uint256 x) private pure returns (uint256) {
                return x > 0 ? MathEx.floorSqrt(x) : 0;
            }
        
            function crossReserveTargetAmount(
                uint256 _sourceReserveBalance,
                uint256 _targetReserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
        
                return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount);
            }
        
            function crossReserveSourceAmount(
                uint256 _sourceReserveBalance,
                uint256 _targetReserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
                require(_amount < _targetReserveBalance, "ERR_INVALID_AMOUNT");
        
                if (_amount == 0) {
                    return 0;
                }
        
                return (_sourceReserveBalance.mul(_amount) - 1) / (_targetReserveBalance - _amount) + 1;
            }
        
            function fundCost(
                uint256 _supply,
                uint256 _reserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_supply > 0, "ERR_INVALID_SUPPLY");
                require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
        
                // special case for 0 amount
                if (_amount == 0) {
                    return 0;
                }
        
                return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
            }
        
            function fundSupplyAmount(
                uint256 _supply,
                uint256 _reserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_supply > 0, "ERR_INVALID_SUPPLY");
                require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
        
                // special case for 0 amount
                if (_amount == 0) {
                    return 0;
                }
        
                return _amount.mul(_supply) / _reserveBalance;
            }
        
            function liquidateReserveAmount(
                uint256 _supply,
                uint256 _reserveBalance,
                uint256 _amount
            ) private pure returns (uint256) {
                // validate input
                require(_supply > 0, "ERR_INVALID_SUPPLY");
                require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
                require(_amount <= _supply, "ERR_INVALID_AMOUNT");
        
                // special case for 0 amount
                if (_amount == 0) {
                    return 0;
                }
        
                // special case for liquidating the entire supply
                if (_amount == _supply) {
                    return _reserveBalance;
                }
        
                return _amount.mul(_reserveBalance) / _supply;
            }
        
            /**
             * @dev returns the network wallet and fees
             *
             * @param reserveBalance0 1st reserve balance
             * @param reserveBalance1 2nd reserve balance
             *
             * @return the network wallet
             * @return the network fee on the 1st reserve
             * @return the network fee on the 2nd reserve
             */
            function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1)
                private
                view
                returns (
                    ITokenHolder,
                    uint256,
                    uint256
                )
            {
                uint256 prevPoint = floorSqrt(_reserveBalancesProduct);
                uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1);
        
                if (prevPoint >= currPoint) {
                    return (ITokenHolder(address(0)), 0, 0);
                }
        
                (ITokenHolder networkFeeWallet, uint32 networkFee) =
                    INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams();
                uint256 n = (currPoint - prevPoint) * networkFee;
                uint256 d = currPoint * PPM_RESOLUTION;
                return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d));
            }
        
            /**
             * @dev transfers funds held by the contract and sends them to an account
             *
             * @param token ERC20 token contract address
             * @param to account to receive the new amount
             * @param amount amount to withdraw
             */
            function safeTransfer(
                IERC20 token,
                address to,
                uint256 amount
            ) private {
                if (amount == 0) {
                    return;
                }
        
                if (token == NATIVE_TOKEN_ADDRESS) {
                    payable(to).transfer(amount);
                } else {
                    token.safeTransfer(to, amount);
                }
            }
        
            /**
             * @dev deprecated since version 28, backward compatibility - use only for earlier versions
             */
            function token() public view override returns (IConverterAnchor) {
                return anchor;
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function transferTokenOwnership(address _newOwner) public override ownerOnly {
                transferAnchorOwnership(_newOwner);
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function acceptTokenOwnership() public override ownerOnly {
                acceptAnchorOwnership();
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function connectors(IERC20 _address)
                public
                view
                override
                returns (
                    uint256,
                    uint32,
                    bool,
                    bool,
                    bool
                )
            {
                uint256 reserveId = __reserveIds[_address];
                if (reserveId != 0) {
                    return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true);
                }
                return (0, 0, false, false, false);
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function connectorTokens(uint256 _index) public view override returns (IERC20) {
                return __reserveTokens[_index];
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function connectorTokenCount() public view override returns (uint16) {
                return reserveTokenCount();
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function getConnectorBalance(IERC20 _connectorToken) public view override returns (uint256) {
                return reserveBalance(_connectorToken);
            }
        
            /**
             * @dev deprecated, backward compatibility
             */
            function getReturn(
                IERC20 _sourceToken,
                IERC20 _targetToken,
                uint256 _amount
            ) public view returns (uint256, uint256) {
                return targetAmountAndFee(_sourceToken, _targetToken, _amount);
            }
        }
        

        File 4 of 8: 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 5 of 8: DSToken
        // File: solidity/contracts/token/interfaces/IERC20Token.sol
        
        // SPDX-License-Identifier: SEE LICENSE IN LICENSE
        pragma solidity 0.6.12;
        
        /*
            ERC20 Standard Token interface
        */
        interface IERC20Token {
            function name() external view returns (string memory);
            function symbol() external view returns (string memory);
            function decimals() external view returns (uint8);
            function totalSupply() external view returns (uint256);
            function balanceOf(address _owner) external view returns (uint256);
            function allowance(address _owner, address _spender) external view returns (uint256);
        
            function transfer(address _to, uint256 _value) external returns (bool);
            function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
            function approve(address _spender, uint256 _value) external returns (bool);
        }
        
        // File: solidity/contracts/utility/Utils.sol
        
        
        pragma solidity 0.6.12;
        
        /**
          * @dev Utilities & Common Modifiers
        */
        contract Utils {
            // verifies that a value is greater than zero
            modifier greaterThanZero(uint256 _value) {
                _greaterThanZero(_value);
                _;
            }
        
            // error message binary size optimization
            function _greaterThanZero(uint256 _value) internal pure {
                require(_value > 0, "ERR_ZERO_VALUE");
            }
        
            // validates an address - currently only checks that it isn't null
            modifier validAddress(address _address) {
                _validAddress(_address);
                _;
            }
        
            // error message binary size optimization
            function _validAddress(address _address) internal pure {
                require(_address != address(0), "ERR_INVALID_ADDRESS");
            }
        
            // verifies that the address is different than this contract address
            modifier notThis(address _address) {
                _notThis(_address);
                _;
            }
        
            // error message binary size optimization
            function _notThis(address _address) internal view {
                require(_address != address(this), "ERR_ADDRESS_IS_SELF");
            }
        }
        
        // File: solidity/contracts/utility/SafeMath.sol
        
        
        pragma solidity 0.6.12;
        
        /**
          * @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, "ERR_OVERFLOW");
                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, "ERR_UNDERFLOW");
                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, "ERR_OVERFLOW");
                return z;
            }
        
            /**
              * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
              *
              * @param _x   dividend
              * @param _y   divisor
              *
              * @return quotient
            */
            function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
                require(_y > 0, "ERR_DIVIDE_BY_ZERO");
                uint256 c = _x / _y;
                return c;
            }
        }
        
        // File: solidity/contracts/token/ERC20Token.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /**
          * @dev ERC20 Standard Token implementation
        */
        contract ERC20Token is IERC20Token, Utils {
            using SafeMath for uint256;
        
        
            string public override name;
            string public override symbol;
            uint8 public override decimals;
            uint256 public override totalSupply;
            mapping (address => uint256) public override balanceOf;
            mapping (address => mapping (address => uint256)) public override 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 memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply) public {
                // validate input
                require(bytes(_name).length > 0, "ERR_INVALID_NAME");
                require(bytes(_symbol).length > 0, "ERR_INVALID_SYMBOL");
        
                name = _name;
                symbol = _symbol;
                decimals = _decimals;
                totalSupply = _totalSupply;
                balanceOf[msg.sender] = _totalSupply;
            }
        
            /**
              * @dev transfers tokens to a given address
              * 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
                virtual
                override
                validAddress(_to)
                returns (bool)
            {
                balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
                balanceOf[_to] = balanceOf[_to].add(_value);
                emit Transfer(msg.sender, _to, _value);
                return true;
            }
        
            /**
              * @dev transfers tokens to a given address on behalf of another address
              * 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
                virtual
                override
                validAddress(_from)
                validAddress(_to)
                returns (bool)
            {
                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 allows another account/contract to transfers tokens on behalf of the caller
              * throws on any error rather then return a false flag to minimize user errors
              *
              * @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
                virtual
                override
                validAddress(_spender)
                returns (bool)
            {
                allowance[msg.sender][_spender] = _value;
                emit Approval(msg.sender, _spender, _value);
                return true;
            }
        }
        
        // File: solidity/contracts/utility/interfaces/IOwned.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Owned contract interface
        */
        interface IOwned {
            // this function isn't since the compiler emits automatically generated getter functions as external
            function owner() external view returns (address);
        
            function transferOwnership(address _newOwner) external;
            function acceptOwnership() external;
        }
        
        // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
        
        
        pragma solidity 0.6.12;
        
        
        /*
            Converter Anchor interface
        */
        interface IConverterAnchor is IOwned {
        }
        
        // File: solidity/contracts/token/interfaces/IDSToken.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /*
            DSToken interface
        */
        interface IDSToken is IConverterAnchor, IERC20Token {
            function issue(address _to, uint256 _amount) external;
            function destroy(address _from, uint256 _amount) external;
        }
        
        // File: solidity/contracts/utility/Owned.sol
        
        
        pragma solidity 0.6.12;
        
        
        /**
          * @dev Provides support and utilities for contract ownership
        */
        contract Owned is IOwned {
            address public override 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 {
                _ownerOnly();
                _;
            }
        
            // error message binary size optimization
            function _ownerOnly() internal view {
                require(msg.sender == owner, "ERR_ACCESS_DENIED");
            }
        
            /**
              * @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 override ownerOnly {
                require(_newOwner != owner, "ERR_SAME_OWNER");
                newOwner = _newOwner;
            }
        
            /**
              * @dev used by a new owner to accept an ownership transfer
            */
            function acceptOwnership() override public {
                require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
                emit OwnerUpdate(owner, newOwner);
                owner = newOwner;
                newOwner = address(0);
            }
        }
        
        // File: solidity/contracts/token/DSToken.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /**
          * @dev DSToken represents a token with dynamic supply.
          * The owner of the token can mint/burn tokens to/from any account.
          *
        */
        contract DSToken is IDSToken, ERC20Token, Owned {
            using SafeMath for uint256;
        
            /**
              * @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 DSToken instance
              *
              * @param _name       token name
              * @param _symbol     token short symbol, minimum 1 character
              * @param _decimals   for display purposes only
            */
            constructor(string memory _name, string memory _symbol, uint8 _decimals)
                public
                ERC20Token(_name, _symbol, _decimals, 0)
            {
            }
        
            /**
              * @dev increases the token supply and sends the new tokens to the given 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
                override
                ownerOnly
                validAddress(_to)
                notThis(_to)
            {
                totalSupply = totalSupply.add(_amount);
                balanceOf[_to] = balanceOf[_to].add(_amount);
        
                emit Issuance(_amount);
                emit Transfer(address(0), _to, _amount);
            }
        
            /**
              * @dev removes tokens from the given 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 override ownerOnly {
                balanceOf[_from] = balanceOf[_from].sub(_amount);
                totalSupply = totalSupply.sub(_amount);
        
                emit Transfer(_from, address(0), _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
                override(IERC20Token, ERC20Token)
                returns (bool)
            {
                return super.transfer(_to, _value);
            }
        
            /**
              * @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
                override(IERC20Token, ERC20Token)
                returns (bool) 
            {
                return super.transferFrom(_from, _to, _value);
            }
        }
        

        File 6 of 8: 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 7 of 8: 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 8 of 8: DSToken
        // File: solidity/contracts/token/interfaces/IERC20Token.sol
        
        // SPDX-License-Identifier: SEE LICENSE IN LICENSE
        pragma solidity 0.6.12;
        
        /*
            ERC20 Standard Token interface
        */
        interface IERC20Token {
            function name() external view returns (string memory);
            function symbol() external view returns (string memory);
            function decimals() external view returns (uint8);
            function totalSupply() external view returns (uint256);
            function balanceOf(address _owner) external view returns (uint256);
            function allowance(address _owner, address _spender) external view returns (uint256);
        
            function transfer(address _to, uint256 _value) external returns (bool);
            function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
            function approve(address _spender, uint256 _value) external returns (bool);
        }
        
        // File: solidity/contracts/utility/Utils.sol
        
        
        pragma solidity 0.6.12;
        
        /**
          * @dev Utilities & Common Modifiers
        */
        contract Utils {
            // verifies that a value is greater than zero
            modifier greaterThanZero(uint256 _value) {
                _greaterThanZero(_value);
                _;
            }
        
            // error message binary size optimization
            function _greaterThanZero(uint256 _value) internal pure {
                require(_value > 0, "ERR_ZERO_VALUE");
            }
        
            // validates an address - currently only checks that it isn't null
            modifier validAddress(address _address) {
                _validAddress(_address);
                _;
            }
        
            // error message binary size optimization
            function _validAddress(address _address) internal pure {
                require(_address != address(0), "ERR_INVALID_ADDRESS");
            }
        
            // verifies that the address is different than this contract address
            modifier notThis(address _address) {
                _notThis(_address);
                _;
            }
        
            // error message binary size optimization
            function _notThis(address _address) internal view {
                require(_address != address(this), "ERR_ADDRESS_IS_SELF");
            }
        }
        
        // File: solidity/contracts/utility/SafeMath.sol
        
        
        pragma solidity 0.6.12;
        
        /**
          * @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, "ERR_OVERFLOW");
                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, "ERR_UNDERFLOW");
                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, "ERR_OVERFLOW");
                return z;
            }
        
            /**
              * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
              *
              * @param _x   dividend
              * @param _y   divisor
              *
              * @return quotient
            */
            function div(uint256 _x, uint256 _y) internal pure returns (uint256) {
                require(_y > 0, "ERR_DIVIDE_BY_ZERO");
                uint256 c = _x / _y;
                return c;
            }
        }
        
        // File: solidity/contracts/token/ERC20Token.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /**
          * @dev ERC20 Standard Token implementation
        */
        contract ERC20Token is IERC20Token, Utils {
            using SafeMath for uint256;
        
        
            string public override name;
            string public override symbol;
            uint8 public override decimals;
            uint256 public override totalSupply;
            mapping (address => uint256) public override balanceOf;
            mapping (address => mapping (address => uint256)) public override 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 memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply) public {
                // validate input
                require(bytes(_name).length > 0, "ERR_INVALID_NAME");
                require(bytes(_symbol).length > 0, "ERR_INVALID_SYMBOL");
        
                name = _name;
                symbol = _symbol;
                decimals = _decimals;
                totalSupply = _totalSupply;
                balanceOf[msg.sender] = _totalSupply;
            }
        
            /**
              * @dev transfers tokens to a given address
              * 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
                virtual
                override
                validAddress(_to)
                returns (bool)
            {
                balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
                balanceOf[_to] = balanceOf[_to].add(_value);
                emit Transfer(msg.sender, _to, _value);
                return true;
            }
        
            /**
              * @dev transfers tokens to a given address on behalf of another address
              * 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
                virtual
                override
                validAddress(_from)
                validAddress(_to)
                returns (bool)
            {
                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 allows another account/contract to transfers tokens on behalf of the caller
              * throws on any error rather then return a false flag to minimize user errors
              *
              * @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
                virtual
                override
                validAddress(_spender)
                returns (bool)
            {
                allowance[msg.sender][_spender] = _value;
                emit Approval(msg.sender, _spender, _value);
                return true;
            }
        }
        
        // File: solidity/contracts/utility/interfaces/IOwned.sol
        
        
        pragma solidity 0.6.12;
        
        /*
            Owned contract interface
        */
        interface IOwned {
            // this function isn't since the compiler emits automatically generated getter functions as external
            function owner() external view returns (address);
        
            function transferOwnership(address _newOwner) external;
            function acceptOwnership() external;
        }
        
        // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
        
        
        pragma solidity 0.6.12;
        
        
        /*
            Converter Anchor interface
        */
        interface IConverterAnchor is IOwned {
        }
        
        // File: solidity/contracts/token/interfaces/IDSToken.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /*
            DSToken interface
        */
        interface IDSToken is IConverterAnchor, IERC20Token {
            function issue(address _to, uint256 _amount) external;
            function destroy(address _from, uint256 _amount) external;
        }
        
        // File: solidity/contracts/utility/Owned.sol
        
        
        pragma solidity 0.6.12;
        
        
        /**
          * @dev Provides support and utilities for contract ownership
        */
        contract Owned is IOwned {
            address public override 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 {
                _ownerOnly();
                _;
            }
        
            // error message binary size optimization
            function _ownerOnly() internal view {
                require(msg.sender == owner, "ERR_ACCESS_DENIED");
            }
        
            /**
              * @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 override ownerOnly {
                require(_newOwner != owner, "ERR_SAME_OWNER");
                newOwner = _newOwner;
            }
        
            /**
              * @dev used by a new owner to accept an ownership transfer
            */
            function acceptOwnership() override public {
                require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
                emit OwnerUpdate(owner, newOwner);
                owner = newOwner;
                newOwner = address(0);
            }
        }
        
        // File: solidity/contracts/token/DSToken.sol
        
        
        pragma solidity 0.6.12;
        
        
        
        
        /**
          * @dev DSToken represents a token with dynamic supply.
          * The owner of the token can mint/burn tokens to/from any account.
          *
        */
        contract DSToken is IDSToken, ERC20Token, Owned {
            using SafeMath for uint256;
        
            /**
              * @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 DSToken instance
              *
              * @param _name       token name
              * @param _symbol     token short symbol, minimum 1 character
              * @param _decimals   for display purposes only
            */
            constructor(string memory _name, string memory _symbol, uint8 _decimals)
                public
                ERC20Token(_name, _symbol, _decimals, 0)
            {
            }
        
            /**
              * @dev increases the token supply and sends the new tokens to the given 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
                override
                ownerOnly
                validAddress(_to)
                notThis(_to)
            {
                totalSupply = totalSupply.add(_amount);
                balanceOf[_to] = balanceOf[_to].add(_amount);
        
                emit Issuance(_amount);
                emit Transfer(address(0), _to, _amount);
            }
        
            /**
              * @dev removes tokens from the given 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 override ownerOnly {
                balanceOf[_from] = balanceOf[_from].sub(_amount);
                totalSupply = totalSupply.sub(_amount);
        
                emit Transfer(_from, address(0), _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
                override(IERC20Token, ERC20Token)
                returns (bool)
            {
                return super.transfer(_to, _value);
            }
        
            /**
              * @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
                override(IERC20Token, ERC20Token)
                returns (bool) 
            {
                return super.transferFrom(_from, _to, _value);
            }
        }